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
TST: check freq in assert_equal
diff --git a/pandas/_testing.py b/pandas/_testing.py index 21e74dafcc944..7ca14546fd46b 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -1429,6 +1429,8 @@ def assert_equal(left, right, **kwargs): if isinstance(left, pd.Index): assert_index_equal(left, right, **kwargs) + if isinstance(left, (pd.DatetimeIndex, pd.TimedeltaIndex)): + assert left.freq == right.freq, (left.freq, right.freq) elif isinstance(left, pd.Series): assert_series_equal(left, right, **kwargs) elif isinstance(left, pd.DataFrame): diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index afdfece842ef9..83d81ccf84b45 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -897,7 +897,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): ) def test_dt64arr_sub_dtscalar(self, box_with_array, ts): # GH#8554, GH#22163 DataFrame op should _not_ return dt64 dtype - idx = pd.date_range("2013-01-01", periods=3) + idx = pd.date_range("2013-01-01", periods=3)._with_freq(None) idx = tm.box_expected(idx, box_with_array) expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) @@ -912,7 +912,7 @@ def test_dt64arr_sub_datetime64_not_ns(self, box_with_array): dt64 = np.datetime64("2013-01-01") assert dt64.dtype == "datetime64[D]" - dti = pd.date_range("20130101", periods=3) + dti = pd.date_range("20130101", periods=3)._with_freq(None) dtarr = tm.box_expected(dti, box_with_array) expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) @@ -926,6 +926,7 @@ def test_dt64arr_sub_datetime64_not_ns(self, box_with_array): def test_dt64arr_sub_timestamp(self, box_with_array): ser = pd.date_range("2014-03-17", periods=2, freq="D", tz="US/Eastern") + ser = ser._with_freq(None) ts = ser[0] ser = tm.box_expected(ser, box_with_array)
Before long we'll move this check into assert_index_equal, for now just want to get validation in place where feasible.
https://api.github.com/repos/pandas-dev/pandas/pulls/33812
2020-04-26T20:07:40Z
2020-04-26T20:53:29Z
2020-04-26T20:53:29Z
2020-04-26T20:55:14Z
BUG: pickle after _with_freq
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 407daf15d5cce..b13a682ef3985 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -410,7 +410,7 @@ def ceil(self, freq, ambiguous="raise", nonexistent="raise"): def _with_freq(self, freq): """ - Helper to set our freq in-place, returning self to allow method chaining. + Helper to get a view on the same data, with a new freq. Parameters ---------- @@ -418,7 +418,7 @@ def _with_freq(self, freq): Returns ------- - self + Same type as self """ # GH#29843 if freq is None: @@ -433,8 +433,9 @@ def _with_freq(self, freq): assert freq == "infer" freq = frequencies.to_offset(self.inferred_freq) - self._freq = freq - return self + arr = self.view() + arr._freq = freq + return arr class DatetimeLikeArrayMixin( diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index f41044db2b49c..ae119e72e37e1 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -44,7 +44,7 @@ from pandas.core.ops import get_op_result_name from pandas.core.tools.timedeltas import to_timedelta -from pandas.tseries.frequencies import DateOffset, to_offset +from pandas.tseries.frequencies import DateOffset from pandas.tseries.offsets import Tick _index_doc_kwargs = dict(ibase._index_doc_kwargs) @@ -678,20 +678,8 @@ def freqstr(self): return self.freq.freqstr def _with_freq(self, freq): - index = self.copy(deep=False) - if freq is None: - # Even if we _can_ have a freq, we might want to set it to None - index._freq = None - elif len(self) == 0 and isinstance(freq, DateOffset): - # Always valid. In the TimedeltaArray case, we assume this - # is a Tick offset. - index._freq = freq - else: - assert freq == "infer", freq - freq = to_offset(self.inferred_freq) - index._freq = freq - - return index + arr = self._data._with_freq(freq) + return type(self)._simple_new(arr, name=self.name) def _shallow_copy(self, values=None, name: Label = lib.no_default): name = self.name if name is lib.no_default else name diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 81fa1a27ac911..e0e5beaf48e20 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -38,6 +38,13 @@ def test_pickle(self): idx_p = tm.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) + def test_pickle_after_set_freq(self): + dti = date_range("20130101", periods=3, tz="US/Eastern", name="foo") + dti = dti._with_freq(None) + + res = tm.round_trip_pickle(dti) + tm.assert_index_equal(res, dti) + def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): # GH7774 index = date_range("20130101", periods=3, tz="US/Eastern") diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 637a2629dda8a..5efa1a75700e0 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -47,6 +47,13 @@ def test_shift(self): def test_pickle_compat_construction(self): pass + def test_pickle_after_set_freq(self): + tdi = timedelta_range("1 day", periods=4, freq="s") + tdi = tdi._with_freq(None) + + res = tm.round_trip_pickle(tdi) + tm.assert_index_equal(res, tdi) + def test_isin(self): index = tm.makeTimedeltaIndex(4)
introduced in #33552
https://api.github.com/repos/pandas-dev/pandas/pulls/33811
2020-04-26T19:51:44Z
2020-04-26T20:52:37Z
2020-04-26T20:52:37Z
2020-04-26T20:55:29Z
BUG: Don't raise in DataFrame.corr with pd.NA
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 08d20af314110..b2d3c588c3bb8 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -569,7 +569,7 @@ Numeric - Bug in :meth:`DataFrame.mean` with ``numeric_only=False`` and either ``datetime64`` dtype or ``PeriodDtype`` column incorrectly raising ``TypeError`` (:issue:`32426`) - Bug in :meth:`DataFrame.count` with ``level="foo"`` and index level ``"foo"`` containing NaNs causes segmentation fault (:issue:`21824`) - Bug in :meth:`DataFrame.diff` with ``axis=1`` returning incorrect results with mixed dtypes (:issue:`32995`) -- +- Bug in :meth:`DataFrame.corr` and :meth:`DataFrame.cov` raising when handling nullable integer columns with ``pandas.NA`` (:issue:`33803`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5810e86f2c8b1..4b4801f4e8c58 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -84,7 +84,6 @@ validate_numeric_casting, ) from pandas.core.dtypes.common import ( - ensure_float64, ensure_int64, ensure_platform_int, infer_dtype_from_object, @@ -7871,16 +7870,16 @@ def corr(self, method="pearson", min_periods=1) -> "DataFrame": numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() - mat = numeric_df.values + mat = numeric_df.astype(float, copy=False).to_numpy() if method == "pearson": - correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods) + correl = libalgos.nancorr(mat, minp=min_periods) elif method == "spearman": - correl = libalgos.nancorr_spearman(ensure_float64(mat), minp=min_periods) + correl = libalgos.nancorr_spearman(mat, minp=min_periods) elif method == "kendall" or callable(method): if min_periods is None: min_periods = 1 - mat = ensure_float64(mat).T + mat = mat.T corrf = nanops.get_corr_func(method) K = len(cols) correl = np.empty((K, K), dtype=float) @@ -8006,19 +8005,19 @@ def cov(self, min_periods=None) -> "DataFrame": numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() - mat = numeric_df.values + mat = numeric_df.astype(float, copy=False).to_numpy() if notna(mat).all(): if min_periods is not None and min_periods > len(mat): - baseCov = np.empty((mat.shape[1], mat.shape[1])) - baseCov.fill(np.nan) + base_cov = np.empty((mat.shape[1], mat.shape[1])) + base_cov.fill(np.nan) else: - baseCov = np.cov(mat.T) - baseCov = baseCov.reshape((len(cols), len(cols))) + base_cov = np.cov(mat.T) + base_cov = base_cov.reshape((len(cols), len(cols))) else: - baseCov = libalgos.nancorr(ensure_float64(mat), cov=True, minp=min_periods) + base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods) - return self._constructor(baseCov, index=idx, columns=cols) + return self._constructor(base_cov, index=idx, columns=cols) def corrwith(self, other, axis=0, drop=False, method="pearson") -> Series: """ diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 5c13b60aae0d0..7d75db55c3073 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -58,6 +58,17 @@ def test_cov(self, float_frame, float_string_frame): ) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])] + ) + def test_cov_nullable_integer(self, other_column): + # https://github.com/pandas-dev/pandas/issues/33803 + data = pd.DataFrame({"a": pd.array([1, 2, None]), "b": other_column}) + result = data.cov() + arr = np.array([[0.5, 0.5], [0.5, 1.0]]) + expected = pd.DataFrame(arr, columns=["a", "b"], index=["a", "b"]) + tm.assert_frame_equal(result, expected) + class TestDataFrameCorr: # DataFrame.corr(), as opposed to DataFrame.corrwith @@ -153,6 +164,22 @@ def test_corr_int(self): df3.cov() df3.corr() + @td.skip_if_no_scipy + @pytest.mark.parametrize( + "nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])] + ) + @pytest.mark.parametrize( + "other_column", + [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.0, 2.0, np.nan])], + ) + @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"]) + def test_corr_nullable_integer(self, nullable_column, other_column, method): + # https://github.com/pandas-dev/pandas/issues/33803 + data = pd.DataFrame({"a": nullable_column, "b": other_column}) + result = data.corr(method=method) + expected = pd.DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"]) + tm.assert_frame_equal(result, expected) + class TestDataFrameCorrWith: def test_corrwith(self, datetime_frame):
- [x] closes #33803 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33809
2020-04-26T19:00:04Z
2020-04-27T23:53:59Z
2020-04-27T23:53:59Z
2020-09-27T03:27:52Z
CLN: use unpack_zerodim_and_defer in timedeltas
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 7cffe6a5a16a9..a460d07e1f6f2 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -27,12 +27,7 @@ pandas_dtype, ) from pandas.core.dtypes.dtypes import DatetimeTZDtype -from pandas.core.dtypes.generic import ( - ABCDataFrame, - ABCIndexClass, - ABCSeries, - ABCTimedeltaIndex, -) +from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex from pandas.core.dtypes.missing import isna from pandas.core import nanops @@ -40,6 +35,7 @@ from pandas.core.arrays import datetimelike as dtl import pandas.core.common as com from pandas.core.construction import extract_array +from pandas.core.ops.common import unpack_zerodim_and_defer from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick @@ -456,12 +452,8 @@ def _addsub_object_array(self, other, op): f"Cannot add/subtract non-tick DateOffset to {type(self).__name__}" ) from err + @unpack_zerodim_and_defer("__mul__") def __mul__(self, other): - other = lib.item_from_zerodim(other) - - if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): - return NotImplemented - if is_scalar(other): # numpy will accept float and int, raise TypeError for others result = self._data * other @@ -492,12 +484,9 @@ def __mul__(self, other): __rmul__ = __mul__ + @unpack_zerodim_and_defer("__truediv__") def __truediv__(self, other): # timedelta / X is well-defined for timedelta-like or numeric X - other = lib.item_from_zerodim(other) - - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) @@ -553,13 +542,9 @@ def __truediv__(self, other): result = self._data / other return type(self)(result) + @unpack_zerodim_and_defer("__rtruediv__") def __rtruediv__(self, other): # X / timedelta is defined only for timedelta-like X - other = lib.item_from_zerodim(other) - - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) if other is NaT: @@ -599,11 +584,9 @@ def __rtruediv__(self, other): f"Cannot divide {other.dtype} data by {type(self).__name__}" ) + @unpack_zerodim_and_defer("__floordiv__") def __floordiv__(self, other): - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - other = lib.item_from_zerodim(other) if is_scalar(other): if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) @@ -665,11 +648,9 @@ def __floordiv__(self, other): dtype = getattr(other, "dtype", type(other).__name__) raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}") + @unpack_zerodim_and_defer("__rfloordiv__") def __rfloordiv__(self, other): - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - other = lib.item_from_zerodim(other) if is_scalar(other): if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) @@ -714,32 +695,23 @@ def __rfloordiv__(self, other): dtype = getattr(other, "dtype", type(other).__name__) raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}") + @unpack_zerodim_and_defer("__mod__") def __mod__(self, other): # Note: This is a naive implementation, can likely be optimized - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - - other = lib.item_from_zerodim(other) if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) return self - (self // other) * other + @unpack_zerodim_and_defer("__rmod__") def __rmod__(self, other): # Note: This is a naive implementation, can likely be optimized - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - - other = lib.item_from_zerodim(other) if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) return other - (other // self) * self + @unpack_zerodim_and_defer("__divmod__") def __divmod__(self, other): # Note: This is a naive implementation, can likely be optimized - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - - other = lib.item_from_zerodim(other) if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other) @@ -747,12 +719,9 @@ def __divmod__(self, other): res2 = self - res1 * other return res1, res2 + @unpack_zerodim_and_defer("__rdivmod__") def __rdivmod__(self, other): # Note: This is a naive implementation, can likely be optimized - if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): - return NotImplemented - - other = lib.item_from_zerodim(other) if isinstance(other, (timedelta, np.timedelta64, Tick)): other = Timedelta(other)
https://api.github.com/repos/pandas-dev/pandas/pulls/33808
2020-04-26T17:00:34Z
2020-04-26T19:24:46Z
2020-04-26T19:24:46Z
2020-04-26T19:33:14Z
TST: Added message to bare pytest.raises in test_join_multi_levels (#…
diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index 1f78c1900d237..61fdafa0c6db2 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -582,13 +582,15 @@ def test_join_multi_levels(self): # invalid cases household.index.name = "foo" - with pytest.raises(ValueError): + with pytest.raises( + ValueError, match="cannot join with no overlapping index names" + ): household.join(portfolio, how="inner") portfolio2 = portfolio.copy() portfolio2.index.set_names(["household_id", "foo"]) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="columns overlap but no suffix specified"): portfolio2.join(portfolio, how="inner") def test_join_multi_levels2(self):
…30999) Updated tests in test_join_multi_levels to include messages for pytest.raises. - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33806
2020-04-26T16:01:09Z
2020-04-26T19:50:19Z
2020-04-26T19:50:18Z
2020-04-26T20:31:07Z
BUG: can't concatenate DataFrame with Series with duplicate keys
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7ad7e8f5a27b0..23a772ae6c405 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -723,6 +723,7 @@ Reshaping - Bug in :meth:`concat` where when passing a non-dict mapping as ``objs`` would raise a ``TypeError`` (:issue:`32863`) - :meth:`DataFrame.agg` now provides more descriptive ``SpecificationError`` message when attempting to aggregating non-existant column (:issue:`32755`) - Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`) +- Bug in :func:`concat` was not allowing for concatenation of ``DataFrame`` and ``Series`` with duplicate keys (:issue:`33654`) - Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index a868e663b06a5..2f66cbf44788d 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -619,10 +619,10 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde for hlevel, level in zip(zipped, levels): to_concat = [] for key, index in zip(hlevel, indexes): - try: - i = level.get_loc(key) - except KeyError as err: - raise ValueError(f"Key {key} not in level {level}") from err + mask = level == key + if not mask.any(): + raise ValueError(f"Key {key} not in level {level}") + i = np.nonzero(level == key)[0][0] to_concat.append(np.repeat(i, len(index))) codes_list.append(np.concatenate(to_concat)) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 7c01664df0607..6625ab86cfed4 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2802,3 +2802,18 @@ def test_concat_multiindex_datetime_object_index(): ) result = concat([s, s2], axis=1) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]]) +def test_duplicate_keys(keys): + # GH 33654 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + s1 = Series([7, 8, 9], name="c") + s2 = Series([10, 11, 12], name="d") + result = concat([df, s1, s2], axis=1, keys=keys) + expected_values = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] + expected_columns = pd.MultiIndex.from_tuples( + [(keys[0], "a"), (keys[0], "b"), (keys[1], "c"), (keys[2], "d")] + ) + expected = DataFrame(expected_values, columns=expected_columns) + tm.assert_frame_equal(result, expected)
- [x] closes #33654 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33805
2020-04-26T10:01:32Z
2020-05-01T16:50:31Z
2020-05-01T16:50:30Z
2020-05-01T17:23:29Z
BUG: support corr and cov functions for custom BaseIndexer rolling windows
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 845f7773c263c..0e87b319add6b 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -175,8 +175,7 @@ Other API changes - Added :meth:`DataFrame.value_counts` (:issue:`5377`) - :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`) - ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`) -- Using a :func:`pandas.api.indexers.BaseIndexer` with ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`) -- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`) +- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew``, ``cov``, ``corr`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`) - Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations. - diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index 082c2f533f3de..12b73646e14bf 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -324,25 +324,3 @@ def func(arg, window, min_periods=None): return cfunc(arg, window, min_periods) return func - - -def validate_baseindexer_support(func_name: Optional[str]) -> None: - # GH 32865: These functions work correctly with a BaseIndexer subclass - BASEINDEXER_WHITELIST = { - "count", - "min", - "max", - "mean", - "sum", - "median", - "std", - "var", - "skew", - "kurt", - "quantile", - } - if isinstance(func_name, str) and func_name not in BASEINDEXER_WHITELIST: - raise NotImplementedError( - f"{func_name} is not supported with using a BaseIndexer " - f"subclasses. You can use .apply() with {func_name}." - ) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 24130c044d186..6c775953e18db 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -48,7 +48,6 @@ calculate_center_offset, calculate_min_periods, get_weighted_roll_func, - validate_baseindexer_support, zsqrt, ) from pandas.core.window.indexers import ( @@ -393,12 +392,11 @@ def _get_cython_func_type(self, func: str) -> Callable: return self._get_roll_func(f"{func}_variable") return partial(self._get_roll_func(f"{func}_fixed"), win=self._get_window()) - def _get_window_indexer(self, window: int, func_name: Optional[str]) -> BaseIndexer: + def _get_window_indexer(self, window: int) -> BaseIndexer: """ Return an indexer class that will compute the window start and end bounds """ if isinstance(self.window, BaseIndexer): - validate_baseindexer_support(func_name) return self.window if self.is_freq_type: return VariableWindowIndexer(index_array=self._on.asi8, window_size=window) @@ -444,7 +442,7 @@ def _apply( blocks, obj = self._create_blocks() block_list = list(blocks) - window_indexer = self._get_window_indexer(window, name) + window_indexer = self._get_window_indexer(window) results = [] exclude: List[Scalar] = [] @@ -1632,20 +1630,23 @@ def quantile(self, quantile, interpolation="linear", **kwargs): """ def cov(self, other=None, pairwise=None, ddof=1, **kwargs): - if isinstance(self.window, BaseIndexer): - validate_baseindexer_support("cov") - if other is None: other = self._selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) - # GH 16058: offset window - if self.is_freq_type: - window = self.win_freq + # GH 32865. We leverage rolling.mean, so we pass + # to the rolling constructors the data used when constructing self: + # window width, frequency data, or a BaseIndexer subclass + if isinstance(self.window, BaseIndexer): + window = self.window else: - window = self._get_window(other) + # GH 16058: offset window + if self.is_freq_type: + window = self.win_freq + else: + window = self._get_window(other) def _get_cov(X, Y): # GH #12373 : rolling functions error on float32 data @@ -1778,15 +1779,19 @@ def _get_cov(X, Y): ) def corr(self, other=None, pairwise=None, **kwargs): - if isinstance(self.window, BaseIndexer): - validate_baseindexer_support("corr") - if other is None: other = self._selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) - window = self._get_window(other) if not self.is_freq_type else self.win_freq + + # GH 32865. We leverage rolling.cov and rolling.std here, so we pass + # to the rolling constructors the data used when constructing self: + # window width, frequency data, or a BaseIndexer subclass + if isinstance(self.window, BaseIndexer): + window = self.window + else: + window = self._get_window(other) if not self.is_freq_type else self.win_freq def _get_corr(a, b): a = a.rolling( diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py index 15e6a904dd11a..df58028dee862 100644 --- a/pandas/tests/window/test_base_indexer.py +++ b/pandas/tests/window/test_base_indexer.py @@ -82,19 +82,6 @@ def get_window_bounds(self, num_values, min_periods, center, closed): df.rolling(indexer, win_type="boxcar") -@pytest.mark.parametrize("func", ["cov", "corr"]) -def test_notimplemented_functions(func): - # GH 32865 - class CustomIndexer(BaseIndexer): - def get_window_bounds(self, num_values, min_periods, center, closed): - return np.array([0, 1]), np.array([1, 2]) - - df = DataFrame({"values": range(2)}) - indexer = CustomIndexer() - with pytest.raises(NotImplementedError, match=f"{func} is not supported"): - getattr(df.rolling(indexer), func)() - - @pytest.mark.parametrize("constructor", [Series, DataFrame]) @pytest.mark.parametrize( "func,np_func,expected,np_kwargs", @@ -210,3 +197,40 @@ def test_rolling_forward_skewness(constructor): ] ) tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "func,expected", + [ + ("cov", [2.0, 2.0, 2.0, 97.0, 2.0, -93.0, 2.0, 2.0, np.nan, np.nan],), + ( + "corr", + [ + 1.0, + 1.0, + 1.0, + 0.8704775290207161, + 0.018229084250926637, + -0.861357304646493, + 1.0, + 1.0, + np.nan, + np.nan, + ], + ), + ], +) +def test_rolling_forward_cov_corr(func, expected): + values1 = np.arange(10).reshape(-1, 1) + values2 = values1 * 2 + values1[5, 0] = 100 + values = np.concatenate([values1, values2], axis=1) + + indexer = FixedForwardWindowIndexer(window_size=3) + rolling = DataFrame(values).rolling(window=indexer, min_periods=3) + # We are interested in checking only pairwise covariance / correlation + result = getattr(rolling, func)().loc[(slice(None), 1), 0] + result = result.reset_index(drop=True) + expected = Series(expected) + expected.name = result.name + tm.assert_equal(result, expected)
- [X] closes #32865 - [X] reverts #33057 - [X] 2 tests added / 2 passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry ## Scope of PR This is the final PR needed to solve #32865. It fixes `cov` and `corr` by passing the correct argument to `rolling` constructors if the functions are called with a custom `BaseIndexer` subclass. A separate test is added for `cov` and `corr` as the previous tests were single-variable and wouldn't work with two columns of data. I also propose we revert #33057. ## Details The reason `cov` and `corr` didn't work was that we were passing `_get_window` results (usually, window width), instead of the `BaseIndexer` subclass to `rolling` constructors called inside the function. Passing `self.window` (when necessary) fixes the issue. The new test asserts only against an explicit array, because shoehorning a comparison against `np.cov` an `np.corrcoef` is ugly (I've tried). Our `rolling.apply` isn't really suited to be called with bivariate statistics functions, and the necessary gymnastics didn't look good to me. I don't believe the minor benefit would be worth, but please say if you think coomparing against numpy is necessary. Thanks to @mroeschke for implementing the `NotImplemented` error-raising behavior in #33057 . Now that all the functions are fixed, I propose we revert that commit. ## Background on the wider issue We currently don't support several rolling window functions when building a rolling window object using a custom class descended from `pandas.api.indexers.Baseindexer`. The implementations were written with backward-looking windows in mind, and this led to these functions breaking. Currently, using these functions returns a `NotImplemented` error thanks to #33057, but ideally we want to update the implementations, so that they will work without a performance hit. This is what I aim to do over a series of PRs. ## Perf notes No changes to algorithms.
https://api.github.com/repos/pandas-dev/pandas/pulls/33804
2020-04-26T08:51:23Z
2020-04-27T18:59:44Z
2020-04-27T18:59:43Z
2020-07-09T15:12:53Z
BUG: incorrect freq in PeriodIndex-Period
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 4ddac12ae8155..f41044db2b49c 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -88,7 +88,7 @@ def wrapped(self, other): if result is NotImplemented: return NotImplemented - new_freq = self._get_addsub_freq(other) + new_freq = self._get_addsub_freq(other, result) result._freq = new_freq return result @@ -451,14 +451,16 @@ def _partial_date_slice( # -------------------------------------------------------------------- # Arithmetic Methods - def _get_addsub_freq(self, other) -> Optional[DateOffset]: + def _get_addsub_freq(self, other, result) -> Optional[DateOffset]: """ Find the freq we expect the result of an addition/subtraction operation to have. """ if is_period_dtype(self.dtype): - # Only used for ops that stay PeriodDtype - return self.freq + if is_period_dtype(result.dtype): + # Only used for ops that stay PeriodDtype + return self.freq + return None elif self.freq is None: return None elif lib.is_scalar(other) and isna(other): diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 4cf1988a33de1..55a547b361eb3 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -1444,8 +1444,13 @@ def test_pi_sub_period(self): tm.assert_index_equal(result, exp) exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") - tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp) - tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp) + result = idx - pd.Period("NaT", freq="M") + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq + + result = pd.Period("NaT", freq="M") - idx + tm.assert_index_equal(result, exp) + assert result.freq == exp.freq def test_pi_sub_pdnat(self): # GH#13071
introduced in #33552
https://api.github.com/repos/pandas-dev/pandas/pulls/33801
2020-04-26T02:11:24Z
2020-04-26T19:23:57Z
2020-04-26T19:23:57Z
2020-04-26T19:34:01Z
IO: Fix feather s3 and http paths
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index cd1cb0b64f74a..188dfd893d66b 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -586,6 +586,7 @@ I/O unsupported HDF file (:issue:`9539`) - Bug in :meth:`~DataFrame.to_parquet` was not raising ``PermissionError`` when writing to a private s3 bucket with invalid creds. (:issue:`27679`) - Bug in :meth:`~DataFrame.to_csv` was silently failing when writing to an invalid s3 bucket. (:issue:`32486`) +- Bug in :meth:`~DataFrame.read_feather` was raising an `ArrowIOError` when reading an s3 or http file path (:issue:`29055`) Plotting ^^^^^^^^ diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index cd7045e7f2d2e..dfa43942fc8b3 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -4,7 +4,7 @@ from pandas import DataFrame, Int64Index, RangeIndex -from pandas.io.common import stringify_path +from pandas.io.common import get_filepath_or_buffer, stringify_path def to_feather(df: DataFrame, path, **kwargs): @@ -98,6 +98,12 @@ def read_feather(path, columns=None, use_threads: bool = True): import_optional_dependency("pyarrow") from pyarrow import feather - path = stringify_path(path) + path, _, _, should_close = get_filepath_or_buffer(path) + + df = feather.read_feather(path, columns=columns, use_threads=bool(use_threads)) + + # s3fs only validates the credentials when the file is closed. + if should_close: + path.close() - return feather.read_feather(path, columns=columns, use_threads=bool(use_threads)) + return df diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index fe71ca77a7dda..f1de15dd34464 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -15,7 +15,7 @@ def tips_file(datapath): @pytest.fixture def jsonl_file(datapath): - """Path a JSONL dataset""" + """Path to a JSONL dataset""" return datapath("io", "parser", "data", "items.jsonl") @@ -26,7 +26,12 @@ def salaries_table(datapath): @pytest.fixture -def s3_resource(tips_file, jsonl_file): +def feather_file(datapath): + return datapath("io", "data", "feather", "feather-0_3_1.feather") + + +@pytest.fixture +def s3_resource(tips_file, jsonl_file, feather_file): """ Fixture for mocking S3 interaction. @@ -58,6 +63,7 @@ def s3_resource(tips_file, jsonl_file): ("tips.csv.gz", tips_file + ".gz"), ("tips.csv.bz2", tips_file + ".bz2"), ("items.jsonl", jsonl_file), + ("simple_dataset.feather", feather_file), ] def add_tips_files(bucket_name): diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 0f09659a24936..000fc605dd5b1 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -13,6 +13,7 @@ from pandas import DataFrame import pandas._testing as tm +from pandas.io.feather_format import read_feather from pandas.io.parsers import read_csv @@ -203,7 +204,6 @@ def test_read_csv_chunked_download(self, s3_resource, caplog): import s3fs df = DataFrame(np.random.randn(100000, 4), columns=list("abcd")) - buf = BytesIO() str_buf = StringIO() df.to_csv(str_buf) @@ -227,3 +227,10 @@ def test_read_s3_with_hash_in_key(self, tips_df): # GH 25945 result = read_csv("s3://pandas-test/tips#1.csv") tm.assert_frame_equal(tips_df, result) + + @td.skip_if_no("pyarrow") + def test_read_feather_s3_file_path(self, feather_file): + # GH 29055 + expected = read_feather(feather_file) + res = read_feather("s3://pandas-test/simple_dataset.feather") + tm.assert_frame_equal(expected, res) diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 0755501ee6285..b43c8e82d4cce 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -159,3 +159,15 @@ def test_path_localpath(self): def test_passthrough_keywords(self): df = tm.makeDataFrame().reset_index() self.check_round_trip(df, write_kwargs=dict(version=1)) + + @td.skip_if_no("pyarrow") + @tm.network + def test_http_path(self, feather_file): + # GH 29055 + url = ( + "https://raw.githubusercontent.com/pandas-dev/pandas/master/" + "pandas/tests/io/data/feather/feather-0_3_1.feather" + ) + expected = pd.read_feather(feather_file) + res = pd.read_feather(url) + tm.assert_frame_equal(expected, res)
- [x] closes #29055 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33798
2020-04-26T01:01:29Z
2020-04-26T19:31:34Z
2020-04-26T19:31:34Z
2020-04-27T23:47:23Z
REF: mix NDArrayBackedExtensionArray into PandasArray
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 0ed9de804c55e..d1f8957859337 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -1,10 +1,11 @@ -from typing import Any, Sequence, TypeVar +from typing import Any, Sequence, Tuple, TypeVar import numpy as np +from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError -from pandas.core.algorithms import take +from pandas.core.algorithms import take, unique from pandas.core.arrays.base import ExtensionArray _T = TypeVar("_T", bound="NDArrayBackedExtensionArray") @@ -60,3 +61,59 @@ def _validate_fill_value(self, fill_value): ValueError """ raise AbstractMethodError(self) + + # ------------------------------------------------------------------------ + + @property + def shape(self) -> Tuple[int, ...]: + return self._ndarray.shape + + def __len__(self) -> int: + return self.shape[0] + + @property + def ndim(self) -> int: + return len(self.shape) + + @property + def size(self) -> int: + return np.prod(self.shape) + + @property + def nbytes(self) -> int: + return self._ndarray.nbytes + + def reshape(self: _T, *args, **kwargs) -> _T: + new_data = self._ndarray.reshape(*args, **kwargs) + return self._from_backing_data(new_data) + + def ravel(self: _T, *args, **kwargs) -> _T: + new_data = self._ndarray.ravel(*args, **kwargs) + return self._from_backing_data(new_data) + + @property + def T(self: _T) -> _T: + new_data = self._ndarray.T + return self._from_backing_data(new_data) + + # ------------------------------------------------------------------------ + + def copy(self: _T) -> _T: + new_data = self._ndarray.copy() + return self._from_backing_data(new_data) + + def repeat(self: _T, repeats, axis=None) -> _T: + """ + Repeat elements of an array. + + See Also + -------- + numpy.ndarray.repeat + """ + nv.validate_repeat(tuple(), dict(axis=axis)) + new_data = self._ndarray.repeat(repeats, axis=axis) + return self._from_backing_data(new_data) + + def unique(self: _T) -> _T: + new_data = unique(self._ndarray) + return self._from_backing_data(new_data) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b5d9386aa62c3..bf14ed44e3a1c 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -9,14 +9,7 @@ from pandas._libs import algos as libalgos, hashtable as htable from pandas._typing import ArrayLike, Dtype, Ordered, Scalar -from pandas.compat.numpy import function as nv -from pandas.util._decorators import ( - Appender, - Substitution, - cache_readonly, - deprecate_kwarg, - doc, -) +from pandas.util._decorators import cache_readonly, deprecate_kwarg, doc from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs from pandas.core.dtypes.cast import ( @@ -52,7 +45,6 @@ from pandas.core.algorithms import _get_data_algo, factorize, take_1d, unique1d from pandas.core.array_algos.transforms import shift from pandas.core.arrays._mixins import _T, NDArrayBackedExtensionArray -from pandas.core.arrays.base import _extension_array_shared_docs from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs import pandas.core.common as com from pandas.core.construction import array, extract_array, sanitize_array @@ -449,14 +441,6 @@ def _formatter(self, boxed=False): # Defer to CategoricalFormatter's formatter. return None - def copy(self) -> "Categorical": - """ - Copy constructor. - """ - return self._constructor( - values=self._codes.copy(), dtype=self.dtype, fastpath=True - ) - def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: """ Coerce this type to another dtype @@ -484,13 +468,6 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: raise ValueError("Cannot convert float NaN to integer") return np.array(self, dtype=dtype, copy=copy) - @cache_readonly - def size(self) -> int: - """ - Return the len of myself. - """ - return self._codes.size - @cache_readonly def itemsize(self) -> int: """ @@ -1194,20 +1171,6 @@ def map(self, mapper): __le__ = _cat_compare_op(operator.le) __ge__ = _cat_compare_op(operator.ge) - # for Series/ndarray like compat - @property - def shape(self): - """ - Shape of the Categorical. - - For internal compatibility with numpy arrays. - - Returns - ------- - shape : tuple - """ - return tuple([len(self._codes)]) - def shift(self, periods, fill_value=None): """ Shift Categorical by desired number of periods. @@ -1313,13 +1276,6 @@ def __setstate__(self, state): for k, v in state.items(): setattr(self, k, v) - @property - def T(self) -> "Categorical": - """ - Return transposed numpy array. - """ - return self - @property def nbytes(self): return self._codes.nbytes + self.dtype.categories.values.nbytes @@ -1865,12 +1821,6 @@ def take_nd(self, indexer, allow_fill: bool = False, fill_value=None): ) return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value) - def __len__(self) -> int: - """ - The length of this Categorical. - """ - return len(self._codes) - def __iter__(self): """ Returns an Iterator over the values of this Categorical. @@ -2337,13 +2287,6 @@ def describe(self): return result - @Substitution(klass="Categorical") - @Appender(_extension_array_shared_docs["repeat"]) - def repeat(self, repeats, axis=None): - nv.validate_repeat(tuple(), dict(axis=axis)) - codes = self._codes.repeat(repeats) - return self._constructor(values=codes, dtype=self.dtype, fastpath=True) - # Implement the ExtensionArray interface @property def _can_hold_na(self): diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index af5834f01c24c..145d6ffe4f078 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -465,24 +465,6 @@ def _from_backing_data(self: _T, arr: np.ndarray) -> _T: # ------------------------------------------------------------------ - @property - def ndim(self) -> int: - return self._data.ndim - - @property - def shape(self): - return self._data.shape - - def reshape(self, *args, **kwargs): - # Note: we drop any freq - data = self._data.reshape(*args, **kwargs) - return type(self)(data, dtype=self.dtype) - - def ravel(self, *args, **kwargs): - # Note: we drop any freq - data = self._data.ravel(*args, **kwargs) - return type(self)(data, dtype=self.dtype) - @property def _box_func(self): """ @@ -532,24 +514,12 @@ def _formatter(self, boxed=False): # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods - @property - def nbytes(self): - return self._data.nbytes - def __array__(self, dtype=None) -> np.ndarray: # used for Timedelta/DatetimeArray, overwritten by PeriodArray if is_object_dtype(dtype): return np.array(list(self), dtype=object) return self._data - @property - def size(self) -> int: - """The number of elements in this array.""" - return np.prod(self.shape) - - def __len__(self) -> int: - return len(self._data) - def __getitem__(self, key): """ This getitem defers to the underlying array, which by-definition can @@ -680,10 +650,6 @@ def view(self, dtype=None): # ------------------------------------------------------------------ # ExtensionArray Interface - def unique(self): - result = unique1d(self.asi8) - return type(self)(result, dtype=self.dtype) - @classmethod def _concat_same_type(cls, to_concat, axis: int = 0): @@ -927,18 +893,6 @@ def searchsorted(self, value, side="left", sorter=None): # TODO: Use datetime64 semantics for sorting, xref GH#29844 return self.asi8.searchsorted(value, side=side, sorter=sorter) - def repeat(self, repeats, *args, **kwargs): - """ - Repeat elements of an array. - - See Also - -------- - numpy.ndarray.repeat - """ - nv.validate_repeat(args, kwargs) - values = self._data.repeat(repeats) - return type(self)(values.view("i8"), dtype=self.dtype) - def value_counts(self, dropna=False): """ Return a Series containing counts of unique values. diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 6806ed2afcf5c..b9384aa1bb092 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -17,8 +17,9 @@ from pandas import compat from pandas.core import nanops -from pandas.core.algorithms import searchsorted, take, unique +from pandas.core.algorithms import searchsorted from pandas.core.array_algos import masked_reductions +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.arrays.base import ExtensionArray, ExtensionOpsMixin from pandas.core.construction import extract_array from pandas.core.indexers import check_array_indexer @@ -120,7 +121,9 @@ def itemsize(self) -> int: return self._dtype.itemsize -class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): +class PandasArray( + NDArrayBackedExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin +): """ A pandas ExtensionArray for NumPy data. @@ -191,6 +194,9 @@ def _from_factorized(cls, values, original) -> "PandasArray": def _concat_same_type(cls, to_concat) -> "PandasArray": return cls(np.concatenate(to_concat)) + def _from_backing_data(self, arr: np.ndarray) -> "PandasArray": + return type(self)(arr) + # ------------------------------------------------------------------------ # Data @@ -272,13 +278,6 @@ def __setitem__(self, key, value) -> None: self._ndarray[key] = value - def __len__(self) -> int: - return len(self._ndarray) - - @property - def nbytes(self) -> int: - return self._ndarray.nbytes - def isna(self) -> np.ndarray: return isna(self._ndarray) @@ -311,17 +310,11 @@ def fillna( new_values = self.copy() return new_values - def take(self, indices, allow_fill=False, fill_value=None) -> "PandasArray": + def _validate_fill_value(self, fill_value): if fill_value is None: # Primarily for subclasses fill_value = self.dtype.na_value - result = take( - self._ndarray, indices, allow_fill=allow_fill, fill_value=fill_value - ) - return type(self)(result) - - def copy(self) -> "PandasArray": - return type(self)(self._ndarray.copy()) + return fill_value def _values_for_argsort(self) -> np.ndarray: return self._ndarray @@ -329,9 +322,6 @@ def _values_for_argsort(self) -> np.ndarray: def _values_for_factorize(self) -> Tuple[np.ndarray, int]: return self._ndarray, -1 - def unique(self) -> "PandasArray": - return type(self)(unique(self._ndarray)) - # ------------------------------------------------------------------------ # Reductions
Share several more methods in NDArrayBackedExtensionArray.
https://api.github.com/repos/pandas-dev/pandas/pulls/33797
2020-04-25T22:12:02Z
2020-04-25T23:56:02Z
2020-04-25T23:56:02Z
2020-04-26T14:09:12Z
CLN: remove unused PeriodEngine methods
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d8e0d9c6bd7ab..871360672c6f0 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -21,14 +21,13 @@ cnp.import_array() cimport pandas._libs.util as util -from pandas._libs.tslibs import Period +from pandas._libs.tslibs import Period, Timedelta from pandas._libs.tslibs.nattype cimport c_NaT as NaT from pandas._libs.tslibs.c_timestamp cimport _Timestamp from pandas._libs.hashtable cimport HashTable from pandas._libs import algos, hashtable as _hash -from pandas._libs.tslibs import Timedelta, period as periodlib from pandas._libs.missing import checknull @@ -501,38 +500,6 @@ cdef class PeriodEngine(Int64Engine): cdef _call_monotonic(self, values): return algos.is_monotonic(values, timelike=True) - def get_indexer(self, values): - cdef: - ndarray[int64_t, ndim=1] ordinals - - super(PeriodEngine, self)._ensure_mapping_populated() - - freq = super(PeriodEngine, self).vgetter().freq - ordinals = periodlib.extract_ordinals(values, freq) - - return self.mapping.lookup(ordinals) - - def get_pad_indexer(self, other: np.ndarray, limit=None) -> np.ndarray: - freq = super(PeriodEngine, self).vgetter().freq - ordinal = periodlib.extract_ordinals(other, freq) - - return algos.pad(self._get_index_values(), - np.asarray(ordinal), limit=limit) - - def get_backfill_indexer(self, other: np.ndarray, limit=None) -> np.ndarray: - freq = super(PeriodEngine, self).vgetter().freq - ordinal = periodlib.extract_ordinals(other, freq) - - return algos.backfill(self._get_index_values(), - np.asarray(ordinal), limit=limit) - - def get_indexer_non_unique(self, targets): - freq = super(PeriodEngine, self).vgetter().freq - ordinal = periodlib.extract_ordinals(targets, freq) - ordinal_array = np.asarray(ordinal) - - return super(PeriodEngine, self).get_indexer_non_unique(ordinal_array) - cdef class BaseMultiIndexCodesEngine: """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 957c01c2dca96..c2e4932a8f8e7 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,6 +1,5 @@ from datetime import datetime, timedelta from typing import Any -import weakref import numpy as np @@ -322,12 +321,6 @@ def _formatter_func(self): # ------------------------------------------------------------------------ # Indexing - @cache_readonly - def _engine(self): - # To avoid a reference cycle, pass a weakref of self._values to _engine_type. - period = weakref.ref(self._values) - return self._engine_type(period, len(self)) - @doc(Index.__contains__) def __contains__(self, key: Any) -> bool: if isinstance(key, Period):
https://api.github.com/repos/pandas-dev/pandas/pulls/33796
2020-04-25T21:00:30Z
2020-04-25T21:39:32Z
2020-04-25T21:39:32Z
2020-04-25T21:40:33Z
DOC: Fix typos and improve parts of docs
diff --git a/doc/source/getting_started/intro_tutorials/02_read_write.rst b/doc/source/getting_started/intro_tutorials/02_read_write.rst index 412a5f9e7485f..12fa2a1e094d6 100644 --- a/doc/source/getting_started/intro_tutorials/02_read_write.rst +++ b/doc/source/getting_started/intro_tutorials/02_read_write.rst @@ -23,7 +23,7 @@ <div class="card-body"> <p class="card-text"> -This tutorial uses the titanic data set, stored as CSV. The data +This tutorial uses the Titanic data set, stored as CSV. The data consists of the following data columns: - PassengerId: Id of every passenger. @@ -61,7 +61,7 @@ How do I read and write tabular data? <ul class="task-bullet"> <li> -I want to analyse the titanic passenger data, available as a CSV file. +I want to analyze the Titanic passenger data, available as a CSV file. .. ipython:: python @@ -134,7 +134,7 @@ strings (``object``). <ul class="task-bullet"> <li> -My colleague requested the titanic data as a spreadsheet. +My colleague requested the Titanic data as a spreadsheet. .. ipython:: python diff --git a/doc/source/getting_started/intro_tutorials/03_subset_data.rst b/doc/source/getting_started/intro_tutorials/03_subset_data.rst index 31f434758876f..8476fee5e1eee 100644 --- a/doc/source/getting_started/intro_tutorials/03_subset_data.rst +++ b/doc/source/getting_started/intro_tutorials/03_subset_data.rst @@ -330,7 +330,7 @@ When using the column names, row labels or a condition expression, use the ``loc`` operator in front of the selection brackets ``[]``. For both the part before and after the comma, you can use a single label, a list of labels, a slice of labels, a conditional expression or a colon. Using -a colon specificies you want to select all rows or columns. +a colon specifies you want to select all rows or columns. .. raw:: html diff --git a/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst b/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst index 7a94c90525027..c7363b94146ac 100644 --- a/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst +++ b/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst @@ -23,7 +23,7 @@ <div class="card-body"> <p class="card-text"> -This tutorial uses the titanic data set, stored as CSV. The data +This tutorial uses the Titanic data set, stored as CSV. The data consists of the following data columns: - PassengerId: Id of every passenger. @@ -72,7 +72,7 @@ Aggregating statistics <ul class="task-bullet"> <li> -What is the average age of the titanic passengers? +What is the average age of the Titanic passengers? .. ipython:: python @@ -95,7 +95,7 @@ across rows by default. <ul class="task-bullet"> <li> -What is the median age and ticket fare price of the titanic passengers? +What is the median age and ticket fare price of the Titanic passengers? .. ipython:: python @@ -148,7 +148,7 @@ Aggregating statistics grouped by category <ul class="task-bullet"> <li> -What is the average age for male versus female titanic passengers? +What is the average age for male versus female Titanic passengers? .. ipython:: python diff --git a/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst b/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst index b28a9012a4ad9..a9652969ffc79 100644 --- a/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst +++ b/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst @@ -23,7 +23,7 @@ <div class="card-body"> <p class="card-text"> -This tutorial uses the titanic data set, stored as CSV. The data +This tutorial uses the Titanic data set, stored as CSV. The data consists of the following data columns: - PassengerId: Id of every passenger. @@ -122,7 +122,7 @@ Sort table rows <ul class="task-bullet"> <li> -I want to sort the titanic data according to the age of the passengers. +I want to sort the Titanic data according to the age of the passengers. .. ipython:: python @@ -138,7 +138,7 @@ I want to sort the titanic data according to the age of the passengers. <ul class="task-bullet"> <li> -I want to sort the titanic data according to the cabin class and age in descending order. +I want to sort the Titanic data according to the cabin class and age in descending order. .. ipython:: python @@ -282,7 +282,7 @@ For more information about :meth:`~DataFrame.pivot_table`, see the user guide se </div> .. note:: - If case you are wondering, :meth:`~DataFrame.pivot_table` is indeed directly linked + In case you are wondering, :meth:`~DataFrame.pivot_table` is indeed directly linked to :meth:`~DataFrame.groupby`. The same result can be derived by grouping on both ``parameter`` and ``location``: @@ -338,7 +338,7 @@ newly created column. The solution is the short version on how to apply :func:`pandas.melt`. The method will *melt* all columns NOT mentioned in ``id_vars`` together into two -columns: A columns with the column header names and a column with the +columns: A column with the column header names and a column with the values itself. The latter column gets by default the name ``value``. The :func:`pandas.melt` method can be defined in more detail: @@ -357,8 +357,8 @@ The result in the same, but in more detail defined: - ``value_vars`` defines explicitly which columns to *melt* together - ``value_name`` provides a custom column name for the values column - instead of the default columns name ``value`` -- ``var_name`` provides a custom column name for the columns collecting + instead of the default column name ``value`` +- ``var_name`` provides a custom column name for the column collecting the column header names. Otherwise it takes the index name or a default ``variable`` @@ -383,7 +383,7 @@ Conversion from wide to long format with :func:`pandas.melt` is explained in the <h4>REMEMBER</h4> - Sorting by one or more columns is supported by ``sort_values`` -- The ``pivot`` function is purely restructering of the data, +- The ``pivot`` function is purely restructuring of the data, ``pivot_table`` supports aggregations - The reverse of ``pivot`` (long to wide format) is ``melt`` (wide to long format) diff --git a/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst b/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst index b6b3c97f2405b..600a75b156ac4 100644 --- a/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst +++ b/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst @@ -305,7 +305,7 @@ More information on join/merge of tables is provided in the user guide section o <div class="shadow gs-callout gs-callout-remember"> <h4>REMEMBER</h4> -- Multiple tables can be concatenated both column as row wise using +- Multiple tables can be concatenated both column-wise and row-wise using the ``concat`` function. - For database-like merging/joining of tables, use the ``merge`` function. diff --git a/doc/source/getting_started/intro_tutorials/09_timeseries.rst b/doc/source/getting_started/intro_tutorials/09_timeseries.rst index 15bdf43543d9a..19351e0e3bc75 100644 --- a/doc/source/getting_started/intro_tutorials/09_timeseries.rst +++ b/doc/source/getting_started/intro_tutorials/09_timeseries.rst @@ -78,7 +78,7 @@ provide any datetime operations (e.g. extract the year, day of the week,…). By applying the ``to_datetime`` function, pandas interprets the strings and convert these to datetime (i.e. ``datetime64[ns, UTC]``) objects. In pandas we call these datetime objects similar to -``datetime.datetime`` from the standard library a :class:`pandas.Timestamp`. +``datetime.datetime`` from the standard library as :class:`pandas.Timestamp`. .. raw:: html @@ -99,7 +99,7 @@ objects. In pandas we call these datetime objects similar to Why are these :class:`pandas.Timestamp` objects useful? Let’s illustrate the added value with some example cases. - What is the start and end date of the time series data set working + What is the start and end date of the time series data set we are working with? .. ipython:: python @@ -214,7 +214,7 @@ Plot the typical :math:`NO_2` pattern during the day of our time series of all s Similar to the previous case, we want to calculate a given statistic (e.g. mean :math:`NO_2`) **for each hour of the day** and we can use the -split-apply-combine approach again. For this case, the datetime property ``hour`` +split-apply-combine approach again. For this case, we use the datetime property ``hour`` of pandas ``Timestamp``, which is also accessible by the ``dt`` accessor. .. raw:: html diff --git a/doc/source/getting_started/intro_tutorials/10_text_data.rst b/doc/source/getting_started/intro_tutorials/10_text_data.rst index a7f3bdc9abcc6..93ad35fb1960b 100644 --- a/doc/source/getting_started/intro_tutorials/10_text_data.rst +++ b/doc/source/getting_started/intro_tutorials/10_text_data.rst @@ -23,7 +23,7 @@ <div class="card-body"> <p class="card-text"> -This tutorial uses the titanic data set, stored as CSV. The data +This tutorial uses the Titanic data set, stored as CSV. The data consists of the following data columns: - PassengerId: Id of every passenger. @@ -102,7 +102,7 @@ Create a new column ``Surname`` that contains the surname of the Passengers by e Using the :meth:`Series.str.split` method, each of the values is returned as a list of 2 elements. The first element is the part before the comma and the -second element the part after the comma. +second element is the part after the comma. .. ipython:: python @@ -135,7 +135,7 @@ More information on extracting parts of strings is available in the user guide s <ul class="task-bullet"> <li> -Extract the passenger data about the Countess on board of the Titanic. +Extract the passenger data about the Countesses on board of the Titanic. .. ipython:: python @@ -145,15 +145,15 @@ Extract the passenger data about the Countess on board of the Titanic. titanic[titanic["Name"].str.contains("Countess")] -(*Interested in her story? See*\ `Wikipedia <https://en.wikipedia.org/wiki/No%C3%ABl_Leslie,_Countess_of_Rothes>`__\ *!*) +(*Interested in her story? See *\ `Wikipedia <https://en.wikipedia.org/wiki/No%C3%ABl_Leslie,_Countess_of_Rothes>`__\ *!*) The string method :meth:`Series.str.contains` checks for each of the values in the column ``Name`` if the string contains the word ``Countess`` and returns for each of the values ``True`` (``Countess`` is part of the name) of -``False`` (``Countess`` is notpart of the name). This output can be used +``False`` (``Countess`` is not part of the name). This output can be used to subselect the data using conditional (boolean) indexing introduced in the :ref:`subsetting of data tutorial <10min_tut_03_subset>`. As there was -only 1 Countess on the Titanic, we get one row as a result. +only one Countess on the Titanic, we get one row as a result. .. raw:: html @@ -161,8 +161,8 @@ only 1 Countess on the Titanic, we get one row as a result. </ul> .. note:: - More powerful extractions on strings is supported, as the - :meth:`Series.str.contains` and :meth:`Series.str.extract` methods accepts `regular + More powerful extractions on strings are supported, as the + :meth:`Series.str.contains` and :meth:`Series.str.extract` methods accept `regular expressions <https://docs.python.org/3/library/re.html>`__, but out of scope of this tutorial. @@ -182,7 +182,7 @@ More information on extracting parts of strings is available in the user guide s <ul class="task-bullet"> <li> -Which passenger of the titanic has the longest name? +Which passenger of the Titanic has the longest name? .. ipython:: python @@ -220,7 +220,7 @@ we can do a selection using the ``loc`` operator, introduced in the <ul class="task-bullet"> <li> -In the ‘Sex’ columns, replace values of ‘male’ by ‘M’ and all ‘female’ values by ‘F’ +In the "Sex" column, replace values of "male" by "M" and values of "female" by "F" .. ipython:: python diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst index 9994287c827e3..93c50fff40305 100644 --- a/doc/source/user_guide/10min.rst +++ b/doc/source/user_guide/10min.rst @@ -664,7 +664,7 @@ Convert the raw grades to a categorical data type. df["grade"] Rename the categories to more meaningful names (assigning to -:meth:`Series.cat.categories` is inplace!). +:meth:`Series.cat.categories` is in place!). .. ipython:: python diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index 055b43bc1e59b..a57998d6605d4 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -68,7 +68,7 @@ the ``.array`` property s.index.array :attr:`~Series.array` will always be an :class:`~pandas.api.extensions.ExtensionArray`. -The exact details of what an :class:`~pandas.api.extensions.ExtensionArray` is and why pandas uses them is a bit +The exact details of what an :class:`~pandas.api.extensions.ExtensionArray` is and why pandas uses them are a bit beyond the scope of this introduction. See :ref:`basics.dtypes` for more. If you know you need a NumPy array, use :meth:`~Series.to_numpy` @@ -518,7 +518,7 @@ data (``True`` by default): Combined with the broadcasting / arithmetic behavior, one can describe various statistical procedures, like standardization (rendering data zero mean and -standard deviation 1), very concisely: +standard deviation of 1), very concisely: .. ipython:: python @@ -700,7 +700,7 @@ By default all columns are used but a subset can be selected using the ``subset` frame = pd.DataFrame(data) frame.value_counts() -Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame: +Similarly, you can get the most frequently occurring value(s), i.e. the mode, of the values in a Series or DataFrame: .. ipython:: python @@ -1022,7 +1022,7 @@ Mixed dtypes ++++++++++++ When presented with mixed dtypes that cannot aggregate, ``.agg`` will only take the valid -aggregations. This is similar to how groupby ``.agg`` works. +aggregations. This is similar to how ``.groupby.agg`` works. .. ipython:: python @@ -1041,7 +1041,7 @@ aggregations. This is similar to how groupby ``.agg`` works. Custom describe +++++++++++++++ -With ``.agg()`` is it possible to easily create a custom describe function, similar +With ``.agg()`` it is possible to easily create a custom describe function, similar to the built in :ref:`describe function <basics.describe>`. .. ipython:: python @@ -1083,7 +1083,8 @@ function name or a user defined function. tsdf.transform('abs') tsdf.transform(lambda x: x.abs()) -Here :meth:`~DataFrame.transform` received a single function; this is equivalent to a ufunc application. +Here :meth:`~DataFrame.transform` received a single function; this is equivalent to a `ufunc +<https://numpy.org/doc/stable/reference/ufuncs.html>`__ application. .. ipython:: python @@ -1457,7 +1458,7 @@ for altering the ``Series.name`` attribute. .. versionadded:: 0.24.0 -The methods :meth:`~DataFrame.rename_axis` and :meth:`~Series.rename_axis` +The methods :meth:`DataFrame.rename_axis` and :meth:`Series.rename_axis` allow specific names of a `MultiIndex` to be changed (as opposed to the labels).
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33793
2020-04-25T18:28:13Z
2020-05-11T00:32:33Z
2020-05-11T00:32:33Z
2020-05-12T07:59:38Z
REF: remove need to override get_indexer_non_unique in DatetimeIndexOpsMixin
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d8e0d9c6bd7ab..5f04c2c7cd14e 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -441,6 +441,10 @@ cdef class DatetimeEngine(Int64Engine): except KeyError: raise KeyError(val) + def get_indexer_non_unique(self, targets): + # we may get datetime64[ns] or timedelta64[ns], cast these to int64 + return super().get_indexer_non_unique(targets.view("i8")) + def get_indexer(self, values): self._ensure_mapping_populated() if values.dtype != self._get_box_dtype(): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5cad76fd18c58..69e9b77633b56 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -13,7 +13,7 @@ from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp from pandas._libs.tslibs.period import IncompatibleFrequency from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import Label +from pandas._typing import DtypeObj, Label from pandas.compat import set_function_name from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, Substitution, cache_readonly, doc @@ -4626,6 +4626,10 @@ def get_indexer_non_unique(self, target): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) + if not self._is_comparable_dtype(target.dtype): + no_matches = -1 * np.ones(self.shape, dtype=np.intp) + return no_matches, no_matches + if is_categorical_dtype(target.dtype): tgt_values = np.asarray(target) else: @@ -4651,16 +4655,33 @@ def get_indexer_for(self, target, **kwargs): indexer, _ = self.get_indexer_non_unique(target, **kwargs) return indexer - def _maybe_promote(self, other): - # A hack, but it works + def _maybe_promote(self, other: "Index"): + """ + When dealing with an object-dtype Index and a non-object Index, see + if we can upcast the object-dtype one to improve performance. + """ if self.inferred_type == "date" and isinstance(other, ABCDatetimeIndex): return type(other)(self), other + elif self.inferred_type == "timedelta" and isinstance(other, ABCTimedeltaIndex): + # TODO: we dont have tests that get here + return type(other)(self), other elif self.inferred_type == "boolean": if not is_object_dtype(self.dtype): return self.astype("object"), other.astype("object") + + if not is_object_dtype(self.dtype) and is_object_dtype(other.dtype): + # Reverse op so we dont need to re-implement on the subclasses + other, self = other._maybe_promote(self) + return self, other + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + """ + Can we compare values of the given dtype to our own? + """ + return True + def groupby(self, values) -> PrettyDict[Hashable, np.ndarray]: """ Group the index labels by a given array of values. diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index cf653a6875a9c..f40fdc469bb92 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -8,14 +8,13 @@ from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones -from pandas._typing import DtypeObj, Label +from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc from pandas.core.dtypes.common import ( ensure_int64, - ensure_platform_int, is_bool_dtype, is_dtype_equal, is_integer, @@ -31,7 +30,7 @@ from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index +from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extension import ( ExtensionIndex, inherit_names, @@ -99,12 +98,6 @@ class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True - def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: - """ - Can we compare values of the given dtype to our own? - """ - raise AbstractMethodError(self) - # ------------------------------------------------------------------------ # Abstract data attributes @@ -430,21 +423,6 @@ def _partial_date_slice( # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] - @Appender(Index.get_indexer_non_unique.__doc__) - def get_indexer_non_unique(self, target): - target = ensure_index(target) - pself, ptarget = self._maybe_promote(target) - if pself is not self or ptarget is not target: - return pself.get_indexer_non_unique(ptarget) - - if not self._is_comparable_dtype(target.dtype): - no_matches = -1 * np.ones(self.shape, dtype=np.intp) - return no_matches, no_matches - - tgt_values = target.asi8 - indexer, missing = self._engine.get_indexer_non_unique(tgt_values) - return ensure_platform_int(indexer), missing - # -------------------------------------------------------------------- __add__ = make_wrapped_arith_op("__add__") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 649d4e6dfc384..1b43176d4b3e3 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -538,11 +538,6 @@ def _validate_partial_date_slice(self, reso: str): # _parsed_string_to_bounds allows it. raise KeyError - def _maybe_promote(self, other): - if other.inferred_type == "date": - other = DatetimeIndex(other) - return self, other - def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index ad698afaedb59..741951d480d18 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -197,11 +197,6 @@ def astype(self, dtype, copy=True): return Index(result.astype("i8"), name=self.name) return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy) - def _maybe_promote(self, other): - if other.inferred_type == "timedelta": - other = TimedeltaIndex(other) - return self, other - def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own?
https://api.github.com/repos/pandas-dev/pandas/pulls/33792
2020-04-25T17:05:31Z
2020-04-25T20:51:26Z
2020-04-25T20:51:26Z
2020-04-25T21:03:17Z
DOC: Link to table schema and remove reference to internal API
diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py index 6061af72901a5..50686594a7576 100644 --- a/pandas/io/json/_table_schema.py +++ b/pandas/io/json/_table_schema.py @@ -211,7 +211,9 @@ def build_table_schema(data, index=True, primary_key=None, version=True): Notes ----- - See `_as_json_table_type` for conversion types. + See `Table Schema + <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for + conversion types. Timedeltas as converted to ISO8601 duration format with 9 decimal places after the seconds field for nanosecond precision.
- [x] closes #33130 - [ ] tests added / passed (Not needed) - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` (Markdown link which will not be shown) - [ ] whatsnew entry (Not needed)
https://api.github.com/repos/pandas-dev/pandas/pulls/33791
2020-04-25T14:59:44Z
2020-04-29T22:49:08Z
2020-04-29T22:49:08Z
2020-04-29T22:49:11Z
CLN: Pass numpy args as kwargs
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index 30768f9bf2b06..d7a14c28cc9ca 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -251,11 +251,16 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): STAT_FUNC_DEFAULTS["dtype"] = None STAT_FUNC_DEFAULTS["out"] = None -PROD_DEFAULTS = SUM_DEFAULTS = STAT_FUNC_DEFAULTS.copy() +SUM_DEFAULTS = STAT_FUNC_DEFAULTS.copy() SUM_DEFAULTS["axis"] = None SUM_DEFAULTS["keepdims"] = False SUM_DEFAULTS["initial"] = None +PROD_DEFAULTS = STAT_FUNC_DEFAULTS.copy() +PROD_DEFAULTS["axis"] = None +PROD_DEFAULTS["keepdims"] = False +PROD_DEFAULTS["initial"] = None + MEDIAN_DEFAULTS = STAT_FUNC_DEFAULTS.copy() MEDIAN_DEFAULTS["overwrite_input"] = False MEDIAN_DEFAULTS["keepdims"] = False diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index e9950e0edaffb..6806ed2afcf5c 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -365,36 +365,14 @@ def max(self, skipna: bool = True, **kwargs) -> Scalar: ) return result - def sum( - self, - axis=None, - dtype=None, - out=None, - keepdims=False, - initial=None, - skipna=True, - min_count=0, - ): - nv.validate_sum( - (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial) - ) + def sum(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: + nv.validate_sum((), kwargs) return nanops.nansum( self._ndarray, axis=axis, skipna=skipna, min_count=min_count ) - def prod( - self, - axis=None, - dtype=None, - out=None, - keepdims=False, - initial=None, - skipna=True, - min_count=0, - ): - nv.validate_prod( - (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial) - ) + def prod(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: + nv.validate_prod((), kwargs) return nanops.nanprod( self._ndarray, axis=axis, skipna=skipna, min_count=min_count )
This is already done in some places for PandasArray, e.g., min / max, and seems cleaner with less boilerplate
https://api.github.com/repos/pandas-dev/pandas/pulls/33789
2020-04-25T14:35:04Z
2020-04-25T21:47:28Z
2020-04-25T21:47:28Z
2020-04-25T22:00:36Z
DOC: Remove ambiguity in fill_value documentation
diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py index 449a477646c02..4ace873f029ae 100644 --- a/pandas/core/ops/docstrings.py +++ b/pandas/core/ops/docstrings.py @@ -399,7 +399,7 @@ def _make_flex_doc(op_name, typ): Return {desc} of series and other, element-wise (binary operator `{op_name}`). Equivalent to ``{equiv}``, but with support to substitute a fill_value for -missing data in one of the inputs. +missing data in either one of the inputs. Parameters ---------- @@ -408,7 +408,7 @@ def _make_flex_doc(op_name, typ): Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing - the result will be missing. + the result of filling (at that location) will be missing. level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level.
- [x] closes #33380 - [ ] tests added / passed (Not needed) - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry (Not needed)
https://api.github.com/repos/pandas-dev/pandas/pulls/33788
2020-04-25T14:30:52Z
2020-04-25T21:48:50Z
2020-04-25T21:48:50Z
2020-04-26T08:00:14Z
BUG, TST, DOC: fix core.missing._akima_interpolate will raise AttributeError
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index e8fdaf0ae5d49..478956666e625 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -538,6 +538,7 @@ Missing - Calling :meth:`fillna` on an empty Series now correctly returns a shallow copied object. The behaviour is now consistent with :class:`Index`, :class:`DataFrame` and a non-empty :class:`Series` (:issue:`32543`). - Bug in :meth:`replace` when argument ``to_replace`` is of type dict/list and is used on a :class:`Series` containing ``<NA>`` was raising a ``TypeError``. The method now handles this by ignoring ``<NA>`` values when doing the comparison for the replacement (:issue:`32621`) - Bug in :meth:`~Series.any` and :meth:`~Series.all` incorrectly returning ``<NA>`` for all ``False`` or all ``True`` values using the nulllable boolean dtype and with ``skipna=False`` (:issue:`33253`) +- Clarified documentation on interpolate with method =akima. The ``der`` parameter must be scalar or None (:issue:`33426`) MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 2acaa808d8324..7b5399ca85e79 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -445,8 +445,9 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0): A 1-D array of real values. `yi`'s length along the interpolation axis must be equal to the length of `xi`. If N-D array, use axis parameter to select correct axis. - x : scalar or array_like of length M. - der : int or list, optional + x : scalar or array_like + Of length M. + der : int, optional How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points), or a list of derivatives to extract. This number @@ -468,12 +469,7 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0): P = interpolate.Akima1DInterpolator(xi, yi, axis=axis) - if der == 0: - return P(x) - elif interpolate._isscalar(der): - return P(x, der=der) - else: - return [P(x, nu) for nu in der] + return P(x, nu=der) def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolate=None): diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index b26cb21bc5f3d..db1c07e1bd276 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -133,17 +133,28 @@ def test_interpolate_akima(self): ser = Series([10, 11, 12, 13]) + # interpolate at new_index where `der` is zero expected = Series( [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00], index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), ) - # interpolate at new_index new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( float ) interp_s = ser.reindex(new_index).interpolate(method="akima") tm.assert_series_equal(interp_s[1:3], expected) + # interpolate at new_index where `der` is a non-zero int + expected = Series( + [11.0, 1.0, 1.0, 1.0, 12.0, 1.0, 1.0, 1.0, 13.0], + index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), + ) + new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( + float + ) + interp_s = ser.reindex(new_index).interpolate(method="akima", der=1) + tm.assert_series_equal(interp_s[1:3], expected) + @td.skip_if_no_scipy def test_interpolate_piecewise_polynomial(self): ser = Series([10, 11, 12, 13])
- [x] closes #33426 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Wasn't sure if this warranted a whatsnew entry since its mostly code cleanup
https://api.github.com/repos/pandas-dev/pandas/pulls/33784
2020-04-25T04:54:33Z
2020-04-26T19:57:38Z
2020-04-26T19:57:38Z
2020-04-26T19:57:42Z
DOC: fix doc for crosstab with Categorical data input
diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst index 7e890962d8da1..c476e33b8ddde 100644 --- a/doc/source/user_guide/reshaping.rst +++ b/doc/source/user_guide/reshaping.rst @@ -471,9 +471,8 @@ If ``crosstab`` receives only two Series, it will provide a frequency table. pd.crosstab(df['A'], df['B']) -Any input passed containing ``Categorical`` data will have **all** of its -categories included in the cross-tabulation, even if the actual data does -not contain any instances of a particular category. +``crosstab`` can also be implemented +to ``Categorical`` data. .. ipython:: python @@ -481,6 +480,15 @@ not contain any instances of a particular category. bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f']) pd.crosstab(foo, bar) +If you want to include **all** of data categories even if the actual data does +not contain any instances of a particular category, you should set ``dropna=False``. + +For example: + +.. ipython:: python + + pd.crosstab(foo, bar, dropna=False) + Normalization ~~~~~~~~~~~~~
Crosstab function should set dropna=False to keep the categories which not appear in the data, but in the DOC, it seems to be inconsistent with the description. Two examples for comparison may be better for users to get this point. https://pandas.pydata.org/docs/dev/user_guide/reshaping.html#cross-tabulations
https://api.github.com/repos/pandas-dev/pandas/pulls/33783
2020-04-25T03:10:39Z
2020-04-27T02:16:26Z
2020-04-27T02:16:26Z
2020-04-27T02:17:12Z
TST: more specific freq attrs
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 3e31c1acbe09d..9be741274c15a 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -331,6 +331,7 @@ def test_constructor_with_datetimelike(self, dtl): def test_constructor_from_index_series_datetimetz(self): idx = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern") + idx = idx._with_freq(None) # freq not preserved in result.categories result = Categorical(idx) tm.assert_index_equal(result.categories, idx) @@ -339,6 +340,7 @@ def test_constructor_from_index_series_datetimetz(self): def test_constructor_from_index_series_timedelta(self): idx = timedelta_range("1 days", freq="D", periods=3) + idx = idx._with_freq(None) # freq not preserved in result.categories result = Categorical(idx) tm.assert_index_equal(result.categories, idx) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 80739b9512953..580c0c7a8cab5 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -302,8 +302,14 @@ def test_round(self, tz_naive_fixture): result = dti.round(freq="2T") expected = dti - pd.Timedelta(minutes=1) + expected = expected._with_freq(None) tm.assert_index_equal(result, expected) + dta = dti._data + result = dta.round(freq="2T") + expected = expected._data._with_freq(None) + tm.assert_datetime_array_equal(result, expected) + def test_array_interface(self, datetime_index): arr = DatetimeArray(datetime_index) diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py index ea8c4b88538d4..d2ab7a386a92d 100644 --- a/pandas/tests/frame/methods/test_tz_convert.py +++ b/pandas/tests/frame/methods/test_tz_convert.py @@ -44,6 +44,12 @@ def test_tz_convert_and_localize(self, fn): # GH7846 df2 = DataFrame(np.ones(5), MultiIndex.from_arrays([l0, l1])) + # freq is not preserved in MultiIndex construction + l1_expected = l1_expected._with_freq(None) + l0_expected = l0_expected._with_freq(None) + l1 = l1._with_freq(None) + l0 = l0._with_freq(None) + df3 = getattr(df2, fn)("US/Pacific", level=0) assert not df3.index.levels[0].equals(l0) tm.assert_index_equal(df3.index.levels[0], l0_expected) diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index f61512b1a62d9..b68e20bee63fc 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -91,7 +91,8 @@ def test_reindex(self, float_frame): # pass non-Index newFrame = float_frame.reindex(list(datetime_series.index)) - tm.assert_index_equal(newFrame.index, datetime_series.index) + expected = datetime_series.index._with_freq(None) + tm.assert_index_equal(newFrame.index, expected) # copy with no axes result = float_frame.reindex() diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index a9d9d0ace8701..9c656dd69abe2 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -54,6 +54,8 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame): float_frame.to_csv(path, index=False) # test roundtrip + # freq does not roundtrip + datetime_frame.index = datetime_frame.index._with_freq(None) datetime_frame.to_csv(path) recons = self.read_csv(path) tm.assert_frame_equal(datetime_frame, recons) @@ -1157,6 +1159,7 @@ def test_to_csv_with_dst_transitions(self): ) for i in [times, times + pd.Timedelta("10s")]: + i = i._with_freq(None) # freq is not preserved by read_csv time_range = np.array(range(len(i)), dtype="int64") df = DataFrame({"A": time_range}, index=i) df.to_csv(path, index=True) @@ -1170,6 +1173,8 @@ def test_to_csv_with_dst_transitions(self): # GH11619 idx = pd.date_range("2015-01-01", "2015-12-31", freq="H", tz="Europe/Paris") + idx = idx._with_freq(None) # freq does not round-trip + idx._data._freq = None # otherwise there is trouble on unpickle df = DataFrame({"values": 1, "idx": idx}, index=idx) with tm.ensure_clean("csv_date_format_with_dst") as path: df.to_csv(path, index=True) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 7cac13efb71f3..6d29ebd7ba795 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -8,7 +8,16 @@ import pytz import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + Timestamp, + date_range, + offsets, +) import pandas._testing as tm from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper @@ -243,17 +252,20 @@ def test_timegrouper_with_reg_groups(self): # single groupers expected = DataFrame( - {"Quantity": [31], "Date": [datetime(2013, 10, 31, 0, 0)]} - ).set_index("Date") + [[31]], + columns=["Quantity"], + index=DatetimeIndex( + [datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date" + ), + ) result = df.groupby(pd.Grouper(freq="1M")).sum() tm.assert_frame_equal(result, expected) result = df.groupby([pd.Grouper(freq="1M")]).sum() tm.assert_frame_equal(result, expected) - expected = DataFrame( - {"Quantity": [31], "Date": [datetime(2013, 11, 30, 0, 0)]} - ).set_index("Date") + expected.index = expected.index.shift(1) + assert expected.index.freq == offsets.MonthEnd() result = df.groupby(pd.Grouper(freq="1M", key="Date")).sum() tm.assert_frame_equal(result, expected) @@ -448,7 +460,7 @@ def test_groupby_groups_datetimeindex(self): for date in dates: result = grouped.get_group(date) data = [[df.loc[date, "A"], df.loc[date, "B"]]] - expected_index = pd.DatetimeIndex([date], name="date") + expected_index = pd.DatetimeIndex([date], name="date", freq="D") expected = pd.DataFrame(data, columns=list("AB"), index=expected_index) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 6ef831a9daaaf..3e7e76bba0dde 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -75,8 +75,10 @@ def test_astype_tzaware_to_tzaware(self): def test_astype_tznaive_to_tzaware(self): # GH 18951: tz-naive to tz-aware idx = date_range("20170101", periods=4) + idx = idx._with_freq(None) # tz_localize does not preserve freq result = idx.astype("datetime64[ns, US/Eastern]") expected = date_range("20170101", periods=4, tz="US/Eastern") + expected = expected._with_freq(None) tm.assert_index_equal(result, expected) def test_astype_str_nat(self): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 1083f1c332705..7b42e9646918e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -383,6 +383,7 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): @pytest.mark.parametrize("klass", [pd.Index, pd.TimedeltaIndex]) def test_constructor_dtypes_timedelta(self, attr, klass): index = pd.timedelta_range("1 days", periods=5) + index = index._with_freq(None) # wont be preserved by constructors dtype = index.dtype values = getattr(index, attr) diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index 558f10d967df6..0415434f01fcf 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -75,6 +75,7 @@ def test_reindex_with_datetimes(): result = ts.reindex(list(ts.index[5:10])) expected = ts[5:10] + expected.index = expected.index._with_freq(None) tm.assert_series_equal(result, expected) result = ts[list(ts.index[5:10])] @@ -91,6 +92,7 @@ def test_reindex_corner(datetime_series): # pass non-Index reindexed = datetime_series.reindex(list(datetime_series.index)) + datetime_series.index = datetime_series.index._with_freq(None) tm.assert_series_equal(datetime_series, reindexed) # bad fill method diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index d43b7efc779b0..39f872394d16b 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -13,6 +13,8 @@ def test_sort_index_name(self, datetime_series): assert result.name == datetime_series.name def test_sort_index(self, datetime_series): + datetime_series.index = datetime_series.index._with_freq(None) + rindex = list(datetime_series.index) random.shuffle(rindex) @@ -45,6 +47,7 @@ def test_sort_index(self, datetime_series): random_order.sort_index(level=0, axis=1) def test_sort_index_inplace(self, datetime_series): + datetime_series.index = datetime_series.index._with_freq(None) # For GH#11402 rindex = list(datetime_series.index) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index e903e850ec36c..0d7fd0529dc1f 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -233,6 +233,8 @@ def get_dir(s): exp_values = pd.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) diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index 510c11a51ca38..708118e950686 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -25,6 +25,8 @@ def read_csv(self, path, **kwargs): return out def test_from_csv(self, datetime_series, string_series): + # freq doesnt round-trip + datetime_series.index = datetime_series.index._with_freq(None) with tm.ensure_clean() as path: datetime_series.to_csv(path, header=False)
Getting ready to check matching freq in assert_index_equal
https://api.github.com/repos/pandas-dev/pandas/pulls/33781
2020-04-25T01:15:24Z
2020-04-26T19:23:05Z
2020-04-26T19:23:05Z
2020-04-26T19:27:20Z
BUG: freq not retained on apply_index
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index cd1cb0b64f74a..e8fdaf0ae5d49 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -462,6 +462,7 @@ Datetimelike - Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`) - Bug in :meth:`DatetimeIndex.tz_localize` incorrectly retaining ``freq`` in some cases where the original freq is no longer valid (:issue:`30511`) - Bug in :meth:`DatetimeIndex.intersection` losing ``freq`` and timezone in some cases (:issue:`33604`) +- Bug in :class:`DatetimeIndex` addition and subtraction with some types of :class:`DateOffset` objects incorrectly retaining an invalid ``freq`` attribute (:issue:`33779`) Timedelta ^^^^^^^^^ diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py index 79a0e0f2c25eb..13cab9be46d37 100644 --- a/pandas/tests/tseries/offsets/test_yqm_offsets.py +++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py @@ -64,6 +64,7 @@ def test_apply_index(cls, n): ser = pd.Series(rng) res = rng + offset + assert res.freq is None # not retained res_v2 = offset.apply_index(rng) assert (res == res_v2).all() assert res[0] == rng[0] + offset diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 8ba10f56f163c..b419d5ccc10b4 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1147,9 +1147,7 @@ def apply(self, other): @apply_index_wraps def apply_index(self, i): shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) - # TODO: going through __new__ raises on call to _validate_frequency; - # are we passing incorrect freq? - return type(i)._simple_new(shifted, freq=i.freq, dtype=i.dtype) + return type(i)._simple_new(shifted, dtype=i.dtype) class MonthEnd(MonthOffset): @@ -1868,11 +1866,7 @@ def apply_index(self, dtindex): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) - # TODO: going through __new__ raises on call to _validate_frequency; - # are we passing incorrect freq? - return type(dtindex)._simple_new( - shifted, freq=dtindex.freq, dtype=dtindex.dtype - ) + return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) class BQuarterEnd(QuarterOffset): @@ -1954,11 +1948,7 @@ def apply_index(self, dtindex): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) - # TODO: going through __new__ raises on call to _validate_frequency; - # are we passing incorrect freq? - return type(dtindex)._simple_new( - shifted, freq=dtindex.freq, dtype=dtindex.dtype - ) + return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33779
2020-04-24T20:41:39Z
2020-04-24T23:23:26Z
2020-04-24T23:23:26Z
2020-04-24T23:28:13Z
CLN: avoid getattr(obj, "values", obj)
diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in index 6e5509a5570e8..c63f368dfae43 100644 --- a/pandas/_libs/hashtable_func_helper.pxi.in +++ b/pandas/_libs/hashtable_func_helper.pxi.in @@ -125,7 +125,7 @@ cpdef value_count_{{dtype}}({{c_type}}[:] values, bint dropna): {{if dtype == 'object'}} def duplicated_{{dtype}}(ndarray[{{dtype}}] values, object keep='first'): {{else}} -def duplicated_{{dtype}}({{c_type}}[:] values, object keep='first'): +def duplicated_{{dtype}}(const {{c_type}}[:] values, object keep='first'): {{endif}} cdef: int ret = 0 diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index e6967630b97ac..eca1733b61a52 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -49,6 +49,7 @@ ABCExtensionArray, ABCIndex, ABCIndexClass, + ABCMultiIndex, ABCSeries, ) from pandas.core.dtypes.missing import isna, na_value_for_dtype @@ -89,6 +90,10 @@ def _ensure_data(values, dtype=None): values : ndarray pandas_dtype : str or dtype """ + if not isinstance(values, ABCMultiIndex): + # extract_array would raise + values = extract_array(values, extract_numpy=True) + # we check some simple dtypes first if is_object_dtype(dtype): return ensure_object(np.asarray(values)), "object" @@ -151,7 +156,6 @@ def _ensure_data(values, dtype=None): elif is_categorical_dtype(values) and ( is_categorical_dtype(dtype) or dtype is None ): - values = getattr(values, "values", values) values = values.codes dtype = "category" diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 220b70ff71b28..66faca29670cb 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -648,7 +648,6 @@ def fillna(self, value=None, method=None, limit=None): ) raise TypeError(msg) - value = getattr(value, "_values", value) self._check_closed_matches(value, name="value") left = self.left.fillna(value=value.left) diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 7f93472c766d7..d9cd2c7be0093 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -102,8 +102,8 @@ def _evaluate_numexpr(op, op_str, a, b): # we were originally called by a reversed op method a, b = b, a - a_value = getattr(a, "values", a) - b_value = getattr(b, "values", b) + a_value = a + b_value = b result = ne.evaluate( f"a_value {op_str} b_value", diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 3b14921528890..05400f63db972 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -37,6 +37,7 @@ from pandas.core.base import DataError, PandasObject, SelectionMixin, ShallowMixin import pandas.core.common as com +from pandas.core.construction import extract_array from pandas.core.indexes.api import Index, ensure_index from pandas.core.util.numba_ import NUMBA_FUNC_CACHE from pandas.core.window.common import ( @@ -252,7 +253,7 @@ def __iter__(self): def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray: """Convert input to numpy arrays for Cython routines""" if values is None: - values = getattr(self._selected_obj, "values", self._selected_obj) + values = extract_array(self._selected_obj, extract_numpy=True) # GH #12373 : rolling functions error on float32 data # make sure the data is coerced to float64
xref #27167 @mroeschke can you pls double-check me on the change in window.rolling
https://api.github.com/repos/pandas-dev/pandas/pulls/33776
2020-04-24T18:45:06Z
2020-04-25T20:48:05Z
2020-04-25T20:48:05Z
2020-04-25T21:03:58Z
REF: misplaced sort_index tests
diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 2c25e1f3740a3..b8eb3494353a9 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -2,11 +2,156 @@ import pytest import pandas as pd -from pandas import CategoricalDtype, DataFrame, IntervalIndex, MultiIndex, Series +from pandas import CategoricalDtype, DataFrame, Index, IntervalIndex, MultiIndex, Series import pandas._testing as tm class TestDataFrameSortIndex: + def test_sort_index_and_reconstruction_doc_example(self): + # doc example + df = DataFrame( + {"value": [1, 2, 3, 4]}, + index=MultiIndex( + levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + assert df.index.is_lexsorted() + assert not df.index.is_monotonic + + # sort it + expected = DataFrame( + {"value": [2, 1, 4, 3]}, + index=MultiIndex( + levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + result = df.sort_index() + assert result.index.is_lexsorted() + assert result.index.is_monotonic + + tm.assert_frame_equal(result, expected) + + # reconstruct + result = df.sort_index().copy() + result.index = result.index._sort_levels_monotonic() + assert result.index.is_lexsorted() + assert result.index.is_monotonic + + tm.assert_frame_equal(result, expected) + + def test_sort_index_non_existent_label_multiindex(self): + # GH#12261 + df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []])) + df.loc["b", "2"] = 1 + df.loc["a", "3"] = 1 + result = df.sort_index().index.is_monotonic + assert result is True + + def test_sort_index_reorder_on_ops(self): + # GH#15687 + df = DataFrame( + np.random.randn(8, 2), + index=MultiIndex.from_product( + [["a", "b"], ["big", "small"], ["red", "blu"]], + names=["letter", "size", "color"], + ), + columns=["near", "far"], + ) + df = df.sort_index() + + def my_func(group): + group.index = ["newz", "newa"] + return group + + result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() + expected = MultiIndex.from_product( + [["a", "b"], ["big", "small"], ["newa", "newz"]], + names=["letter", "size", None], + ) + + tm.assert_index_equal(result.index, expected) + + def test_sort_index_nan_multiindex(self): + # GH#14784 + # incorrect sorting w.r.t. nans + tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] + mi = MultiIndex.from_tuples(tuples) + + df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) + s = Series(np.arange(4), index=mi) + + df2 = DataFrame( + { + "date": pd.DatetimeIndex( + [ + "20121002", + "20121007", + "20130130", + "20130202", + "20130305", + "20121002", + "20121207", + "20130130", + "20130202", + "20130305", + "20130202", + "20130305", + ] + ), + "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], + "whole_cost": [ + 1790, + np.nan, + 280, + 259, + np.nan, + 623, + 90, + 312, + np.nan, + 301, + 359, + 801, + ], + "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], + } + ).set_index(["date", "user_id"]) + + # sorting frame, default nan position is last + result = df.sort_index() + expected = df.iloc[[3, 0, 2, 1], :] + tm.assert_frame_equal(result, expected) + + # sorting frame, nan position last + result = df.sort_index(na_position="last") + expected = df.iloc[[3, 0, 2, 1], :] + tm.assert_frame_equal(result, expected) + + # sorting frame, nan position first + result = df.sort_index(na_position="first") + expected = df.iloc[[1, 2, 3, 0], :] + tm.assert_frame_equal(result, expected) + + # sorting frame with removed rows + result = df2.dropna().sort_index() + expected = df2.sort_index().dropna() + tm.assert_frame_equal(result, expected) + + # sorting series, default nan position is last + result = s.sort_index() + expected = s.iloc[[3, 0, 2, 1]] + tm.assert_series_equal(result, expected) + + # sorting series, nan position last + result = s.sort_index(na_position="last") + expected = s.iloc[[3, 0, 2, 1]] + tm.assert_series_equal(result, expected) + + # sorting series, nan position first + result = s.sort_index(na_position="first") + expected = s.iloc[[1, 2, 3, 0]] + tm.assert_series_equal(result, expected) + def test_sort_index_nan(self): # GH#3917 @@ -318,3 +463,196 @@ def test_sort_index_ignore_index_multi_index( tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=mi)) + + def test_sort_index_categorical_multiindex(self): + # GH#15058 + df = DataFrame( + { + "a": range(6), + "l1": pd.Categorical( + ["a", "a", "b", "b", "c", "c"], + categories=["c", "a", "b"], + ordered=True, + ), + "l2": [0, 1, 0, 1, 0, 1], + } + ) + result = df.set_index(["l1", "l2"]).sort_index() + expected = DataFrame( + [4, 5, 0, 1, 2, 3], + columns=["a"], + index=MultiIndex( + levels=[ + pd.CategoricalIndex( + ["c", "a", "b"], + categories=["c", "a", "b"], + ordered=True, + name="l1", + dtype="category", + ), + [0, 1], + ], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=["l1", "l2"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_sort_index_and_reconstruction(self): + + # GH#15622 + # lexsortedness should be identical + # across MultiIndex construction methods + + df = DataFrame([[1, 1], [2, 2]], index=list("ab")) + expected = DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=MultiIndex.from_tuples( + [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] + ), + ) + assert expected.index.is_lexsorted() + + result = DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=MultiIndex.from_product([[0.5, 0.8], list("ab")]), + ) + result = result.sort_index() + assert result.index.is_lexsorted() + assert result.index.is_monotonic + + tm.assert_frame_equal(result, expected) + + result = DataFrame( + [[1, 1], [2, 2], [1, 1], [2, 2]], + index=MultiIndex( + levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] + ), + ) + result = result.sort_index() + assert result.index.is_lexsorted() + + tm.assert_frame_equal(result, expected) + + concatted = pd.concat([df, df], keys=[0.8, 0.5]) + result = concatted.sort_index() + + assert result.index.is_lexsorted() + assert result.index.is_monotonic + + tm.assert_frame_equal(result, expected) + + # GH#14015 + df = DataFrame( + [[1, 2], [6, 7]], + columns=MultiIndex.from_tuples( + [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], + names=["l1", "Date"], + ), + ) + + df.columns.set_levels( + pd.to_datetime(df.columns.levels[1]), level=1, inplace=True + ) + assert not df.columns.is_lexsorted() + assert not df.columns.is_monotonic + result = df.sort_index(axis=1) + assert result.columns.is_lexsorted() + assert result.columns.is_monotonic + result = df.sort_index(axis=1, level=1) + assert result.columns.is_lexsorted() + assert result.columns.is_monotonic + + # TODO: better name, de-duplicate with test_sort_index_level above + def test_sort_index_level2(self): + mi = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + frame = DataFrame( + np.random.randn(10, 3), + index=mi, + columns=Index(["A", "B", "C"], name="exp"), + ) + + df = frame.copy() + df.index = np.arange(len(df)) + + # axis=1 + + # series + a_sorted = frame["A"].sort_index(level=0) + + # preserve names + assert a_sorted.index.names == frame.index.names + + # inplace + rs = frame.copy() + rs.sort_index(level=0, inplace=True) + tm.assert_frame_equal(rs, frame.sort_index(level=0)) + + def test_sort_index_level_large_cardinality(self): + + # GH#2684 (int64) + index = MultiIndex.from_arrays([np.arange(4000)] * 3) + df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) + + # it works! + result = df.sort_index(level=0) + assert result.index.lexsort_depth == 3 + + # GH#2684 (int32) + index = MultiIndex.from_arrays([np.arange(4000)] * 3) + df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) + + # it works! + result = df.sort_index(level=0) + assert (result.dtypes.values == df.dtypes.values).all() + assert result.index.lexsort_depth == 3 + + def test_sort_index_level_by_name(self): + mi = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + frame = DataFrame( + np.random.randn(10, 3), + index=mi, + columns=Index(["A", "B", "C"], name="exp"), + ) + + frame.index.names = ["first", "second"] + result = frame.sort_index(level="second") + expected = frame.sort_index(level=1) + tm.assert_frame_equal(result, expected) + + def test_sort_index_level_mixed(self): + mi = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + frame = DataFrame( + np.random.randn(10, 3), + index=mi, + columns=Index(["A", "B", "C"], name="exp"), + ) + + sorted_before = frame.sort_index(level=1) + + df = frame.copy() + df["foo"] = "bar" + sorted_after = df.sort_index(level=1) + tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) + + dft = frame.T + sorted_before = dft.sort_index(level=1, axis=1) + dft["foo", "three"] = "bar" + + sorted_after = dft.sort_index(level=1, axis=1) + tm.assert_frame_equal( + sorted_before.drop([("foo", "three")], axis=1), + sorted_after.drop([("foo", "three")], axis=1), + ) diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 2d4fdfd5a3950..18a3322ce94d8 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -170,3 +170,26 @@ def test_sort_index_ignore_index( tm.assert_series_equal(result_ser, expected) tm.assert_series_equal(ser, Series(original_list)) + + def test_sort_index_ascending_list(self): + # GH#16934 + + # Set up a Series with a three level MultiIndex + arrays = [ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + [4, 3, 2, 1, 4, 3, 2, 1], + ] + tuples = zip(*arrays) + mi = MultiIndex.from_tuples(tuples, names=["first", "second", "third"]) + ser = Series(range(8), index=mi) + + # Sort with boolean ascending + result = ser.sort_index(level=["third", "first"], ascending=False) + expected = ser.iloc[[4, 0, 5, 1, 6, 2, 7, 3]] + tm.assert_series_equal(result, expected) + + # Sort with list of boolean ascending + result = ser.sort_index(level=["third", "first"], ascending=[False, True]) + expected = ser.iloc[[0, 4, 1, 5, 2, 6, 3, 7]] + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index dd0bac683c35c..884c169cdeed6 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1802,229 +1802,6 @@ def test_sorting_repr_8017(self): result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) - def test_sort_index_level(self): - df = self.frame.copy() - df.index = np.arange(len(df)) - - # axis=1 - - # series - a_sorted = self.frame["A"].sort_index(level=0) - - # preserve names - assert a_sorted.index.names == self.frame.index.names - - # inplace - rs = self.frame.copy() - rs.sort_index(level=0, inplace=True) - tm.assert_frame_equal(rs, self.frame.sort_index(level=0)) - - def test_sort_index_level_large_cardinality(self): - - # #2684 (int64) - index = MultiIndex.from_arrays([np.arange(4000)] * 3) - df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) - - # it works! - result = df.sort_index(level=0) - assert result.index.lexsort_depth == 3 - - # #2684 (int32) - index = MultiIndex.from_arrays([np.arange(4000)] * 3) - df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) - - # it works! - result = df.sort_index(level=0) - assert (result.dtypes.values == df.dtypes.values).all() - assert result.index.lexsort_depth == 3 - - def test_sort_index_level_by_name(self): - self.frame.index.names = ["first", "second"] - result = self.frame.sort_index(level="second") - expected = self.frame.sort_index(level=1) - tm.assert_frame_equal(result, expected) - - def test_sort_index_level_mixed(self): - sorted_before = self.frame.sort_index(level=1) - - df = self.frame.copy() - df["foo"] = "bar" - sorted_after = df.sort_index(level=1) - tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) - - dft = self.frame.T - sorted_before = dft.sort_index(level=1, axis=1) - dft["foo", "three"] = "bar" - - sorted_after = dft.sort_index(level=1, axis=1) - tm.assert_frame_equal( - sorted_before.drop([("foo", "three")], axis=1), - sorted_after.drop([("foo", "three")], axis=1), - ) - - def test_sort_index_categorical_multiindex(self): - # GH 15058 - df = DataFrame( - { - "a": range(6), - "l1": pd.Categorical( - ["a", "a", "b", "b", "c", "c"], - categories=["c", "a", "b"], - ordered=True, - ), - "l2": [0, 1, 0, 1, 0, 1], - } - ) - result = df.set_index(["l1", "l2"]).sort_index() - expected = DataFrame( - [4, 5, 0, 1, 2, 3], - columns=["a"], - index=MultiIndex( - levels=[ - pd.CategoricalIndex( - ["c", "a", "b"], - categories=["c", "a", "b"], - ordered=True, - name="l1", - dtype="category", - ), - [0, 1], - ], - codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], - names=["l1", "l2"], - ), - ) - tm.assert_frame_equal(result, expected) - - def test_sort_index_and_reconstruction(self): - - # 15622 - # lexsortedness should be identical - # across MultiIndex construction methods - - df = DataFrame([[1, 1], [2, 2]], index=list("ab")) - expected = DataFrame( - [[1, 1], [2, 2], [1, 1], [2, 2]], - index=MultiIndex.from_tuples( - [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] - ), - ) - assert expected.index.is_lexsorted() - - result = DataFrame( - [[1, 1], [2, 2], [1, 1], [2, 2]], - index=MultiIndex.from_product([[0.5, 0.8], list("ab")]), - ) - result = result.sort_index() - assert result.index.is_lexsorted() - assert result.index.is_monotonic - - tm.assert_frame_equal(result, expected) - - result = DataFrame( - [[1, 1], [2, 2], [1, 1], [2, 2]], - index=MultiIndex( - levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] - ), - ) - result = result.sort_index() - assert result.index.is_lexsorted() - - tm.assert_frame_equal(result, expected) - - concatted = pd.concat([df, df], keys=[0.8, 0.5]) - result = concatted.sort_index() - - assert result.index.is_lexsorted() - assert result.index.is_monotonic - - tm.assert_frame_equal(result, expected) - - # 14015 - df = DataFrame( - [[1, 2], [6, 7]], - columns=MultiIndex.from_tuples( - [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], - names=["l1", "Date"], - ), - ) - - df.columns.set_levels( - pd.to_datetime(df.columns.levels[1]), level=1, inplace=True - ) - assert not df.columns.is_lexsorted() - assert not df.columns.is_monotonic - result = df.sort_index(axis=1) - assert result.columns.is_lexsorted() - assert result.columns.is_monotonic - result = df.sort_index(axis=1, level=1) - assert result.columns.is_lexsorted() - assert result.columns.is_monotonic - - def test_sort_index_and_reconstruction_doc_example(self): - # doc example - df = DataFrame( - {"value": [1, 2, 3, 4]}, - index=MultiIndex( - levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] - ), - ) - assert df.index.is_lexsorted() - assert not df.index.is_monotonic - - # sort it - expected = DataFrame( - {"value": [2, 1, 4, 3]}, - index=MultiIndex( - levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] - ), - ) - result = df.sort_index() - assert result.index.is_lexsorted() - assert result.index.is_monotonic - - tm.assert_frame_equal(result, expected) - - # reconstruct - result = df.sort_index().copy() - result.index = result.index._sort_levels_monotonic() - assert result.index.is_lexsorted() - assert result.index.is_monotonic - - tm.assert_frame_equal(result, expected) - - def test_sort_index_non_existent_label_multiindex(self): - # GH 12261 - df = DataFrame(0, columns=[], index=pd.MultiIndex.from_product([[], []])) - df.loc["b", "2"] = 1 - df.loc["a", "3"] = 1 - result = df.sort_index().index.is_monotonic - assert result is True - - def test_sort_index_reorder_on_ops(self): - # 15687 - df = DataFrame( - np.random.randn(8, 2), - index=MultiIndex.from_product( - [["a", "b"], ["big", "small"], ["red", "blu"]], - names=["letter", "size", "color"], - ), - columns=["near", "far"], - ) - df = df.sort_index() - - def my_func(group): - group.index = ["newz", "newa"] - return group - - result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() - expected = MultiIndex.from_product( - [["a", "b"], ["big", "small"], ["newa", "newz"]], - names=["letter", "size", None], - ) - - tm.assert_index_equal(result.index, expected) - def test_sort_non_lexsorted(self): # degenerate case where we sort but don't # have a satisfying result :< @@ -2051,110 +1828,6 @@ def test_sort_non_lexsorted(self): result = sorted.loc[pd.IndexSlice["B":"C", "a":"c"], :] tm.assert_frame_equal(result, expected) - def test_sort_index_nan(self): - # GH 14784 - # incorrect sorting w.r.t. nans - tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] - mi = MultiIndex.from_tuples(tuples) - - df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) - s = Series(np.arange(4), index=mi) - - df2 = DataFrame( - { - "date": pd.to_datetime( - [ - "20121002", - "20121007", - "20130130", - "20130202", - "20130305", - "20121002", - "20121207", - "20130130", - "20130202", - "20130305", - "20130202", - "20130305", - ] - ), - "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], - "whole_cost": [ - 1790, - np.nan, - 280, - 259, - np.nan, - 623, - 90, - 312, - np.nan, - 301, - 359, - 801, - ], - "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], - } - ).set_index(["date", "user_id"]) - - # sorting frame, default nan position is last - result = df.sort_index() - expected = df.iloc[[3, 0, 2, 1], :] - tm.assert_frame_equal(result, expected) - - # sorting frame, nan position last - result = df.sort_index(na_position="last") - expected = df.iloc[[3, 0, 2, 1], :] - tm.assert_frame_equal(result, expected) - - # sorting frame, nan position first - result = df.sort_index(na_position="first") - expected = df.iloc[[1, 2, 3, 0], :] - tm.assert_frame_equal(result, expected) - - # sorting frame with removed rows - result = df2.dropna().sort_index() - expected = df2.sort_index().dropna() - tm.assert_frame_equal(result, expected) - - # sorting series, default nan position is last - result = s.sort_index() - expected = s.iloc[[3, 0, 2, 1]] - tm.assert_series_equal(result, expected) - - # sorting series, nan position last - result = s.sort_index(na_position="last") - expected = s.iloc[[3, 0, 2, 1]] - tm.assert_series_equal(result, expected) - - # sorting series, nan position first - result = s.sort_index(na_position="first") - expected = s.iloc[[1, 2, 3, 0]] - tm.assert_series_equal(result, expected) - - def test_sort_ascending_list(self): - # GH: 16934 - - # Set up a Series with a three level MultiIndex - arrays = [ - ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], - ["one", "two", "one", "two", "one", "two", "one", "two"], - [4, 3, 2, 1, 4, 3, 2, 1], - ] - tuples = zip(*arrays) - mi = MultiIndex.from_tuples(tuples, names=["first", "second", "third"]) - s = Series(range(8), index=mi) - - # Sort with boolean ascending - result = s.sort_index(level=["third", "first"], ascending=False) - expected = s.iloc[[4, 0, 5, 1, 6, 2, 7, 3]] - tm.assert_series_equal(result, expected) - - # Sort with list of boolean ascending - result = s.sort_index(level=["third", "first"], ascending=[False, True]) - expected = s.iloc[[0, 4, 1, 5, 2, 6, 3, 7]] - tm.assert_series_equal(result, expected) - @pytest.mark.parametrize( "keys, expected", [
https://api.github.com/repos/pandas-dev/pandas/pulls/33774
2020-04-24T18:18:03Z
2020-04-24T21:33:30Z
2020-04-24T21:33:30Z
2020-04-24T22:19:20Z
TST: more accurate freq attr in `expected`s
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index a8e9ad9ff7cc9..79fcb5e9478c3 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -2052,6 +2052,7 @@ def test_dti_add_tdi(self, tz_naive_fixture): dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = pd.date_range("2017-01-01", periods=10, tz=tz) + expected._set_freq(None) # add with TimdeltaIndex result = dti + tdi @@ -2073,6 +2074,7 @@ def test_dti_iadd_tdi(self, tz_naive_fixture): dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = pd.date_range("2017-01-01", periods=10, tz=tz) + expected._set_freq(None) # iadd with TimdeltaIndex result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) @@ -2098,6 +2100,7 @@ def test_dti_sub_tdi(self, tz_naive_fixture): dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D") + expected = expected._with_freq(None) # sub with TimedeltaIndex result = dti - tdi @@ -2121,6 +2124,7 @@ def test_dti_isub_tdi(self, tz_naive_fixture): dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D") + expected = expected._with_freq(None) # isub with TimedeltaIndex result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 202e30287881f..0675ba874846b 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -165,7 +165,7 @@ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box): # GH#19333 index = numeric_idx - expected = pd.timedelta_range("0 days", "4 days") + expected = pd.TimedeltaIndex([pd.Timedelta(days=n) for n in range(5)]) index = tm.box_expected(index, box) expected = tm.box_expected(expected, box) @@ -974,7 +974,7 @@ def check(series, other): tm.assert_almost_equal(np.asarray(result), expected) assert result.name == series.name - tm.assert_index_equal(result.index, series.index) + tm.assert_index_equal(result.index, series.index._with_freq(None)) tser = tm.makeTimeSeries().rename("ts") check(tser, tser * 2) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 8387e4d708662..3ffdc87ff84c8 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -403,9 +403,7 @@ def _check(result, expected): _check(result, expected) result = dti_tz - td - expected = DatetimeIndex( - ["20121231", "20130101", "20130102"], tz="US/Eastern", freq="D" - ) + expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern") tm.assert_index_equal(result, expected) def test_dti_tdi_numeric_ops(self): @@ -515,7 +513,13 @@ def test_timedelta(self, freq): result2 = DatetimeIndex(s - np.timedelta64(100000000)) result3 = rng - np.timedelta64(100000000) result4 = DatetimeIndex(s - pd.offsets.Hour(1)) + + assert result1.freq == rng.freq + result1 = result1._with_freq(None) tm.assert_index_equal(result1, result4) + + assert result3.freq == rng.freq + result3 = result3._with_freq(None) tm.assert_index_equal(result2, result3) def test_tda_add_sub_index(self): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index c0e1eeb8f4eec..957ca138498d9 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -266,6 +266,8 @@ def test_ensure_copied_data(self, indices): result = index_type(indices.values, copy=True, **init_kwargs) if is_datetime64tz_dtype(indices.dtype): result = result.tz_localize("UTC").tz_convert(indices.tz) + if isinstance(indices, (DatetimeIndex, TimedeltaIndex)): + indices._set_freq(None) tm.assert_index_equal(indices, result) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index e109c7a4f1c8d..08706dce7e1e0 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -368,7 +368,8 @@ def test_factorize_tz(self, tz_naive_fixture): for obj in [idx, pd.Series(idx)]: arr, res = obj.factorize() tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(res, base) + expected = base._with_freq(None) + tm.assert_index_equal(res, expected) def test_factorize_dst(self): # GH 13750 diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index c55b0481c1041..f0fe5e9b293fc 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -134,11 +134,14 @@ def test_value_counts_unique(self, tz_naive_fixture): exp_idx = pd.date_range("2011-01-01 18:00", freq="-1H", periods=10, tz=tz) expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64") + expected.index._set_freq(None) for obj in [idx, Series(idx)]: + tm.assert_series_equal(obj.value_counts(), expected) expected = pd.date_range("2011-01-01 09:00", freq="H", periods=10, tz=tz) + expected = expected._with_freq(None) tm.assert_index_equal(idx.unique(), expected) idx = DatetimeIndex( @@ -274,7 +277,8 @@ def test_drop_duplicates_metadata(self, freq_sample): idx_dup = idx.append(idx) assert idx_dup.freq is None # freq is reset result = idx_dup.drop_duplicates() - tm.assert_index_equal(idx, result) + expected = idx._with_freq(None) + tm.assert_index_equal(result, expected) assert result.freq is None @pytest.mark.parametrize( diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 7182d05b77be3..df6e2dac72f95 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -285,16 +285,17 @@ def test_intersection_empty(self, tz_aware_fixture, freq): assert result.freq == rng.freq # no overlap GH#33604 + check_freq = freq != "T" # We don't preserve freq on non-anchored offsets result = rng[:3].intersection(rng[-3:]) tm.assert_index_equal(result, rng[:0]) - if freq != "T": + if check_freq: # We don't preserve freq on non-anchored offsets assert result.freq == rng.freq # swapped left and right result = rng[-3:].intersection(rng[:3]) tm.assert_index_equal(result, rng[:0]) - if freq != "T": + if check_freq: # We don't preserve freq on non-anchored offsets assert result.freq == rng.freq diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 8628ce7ade212..ea68e8759c123 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -271,6 +271,7 @@ def test_tz_convert_roundtrip(self, tz_aware_fixture): tm.assert_index_equal(reset, expected) assert reset.tzinfo is None expected = converted.tz_convert("UTC").tz_localize(None) + expected = expected._with_freq("infer") tm.assert_index_equal(reset, expected) def test_dti_tz_convert_tzlocal(self): @@ -352,8 +353,9 @@ def test_dti_tz_localize_ambiguous_infer(self, tz): ] di = DatetimeIndex(times) localized = di.tz_localize(tz, ambiguous="infer") - tm.assert_index_equal(dr, localized) - tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz, ambiguous="infer")) + expected = dr._with_freq(None) + tm.assert_index_equal(expected, localized) + tm.assert_index_equal(expected, DatetimeIndex(times, tz=tz, ambiguous="infer")) # When there is no dst transition, nothing special happens dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=pd.offsets.Hour()) @@ -458,7 +460,8 @@ def test_dti_tz_localize_roundtrip(self, tz_aware_fixture): localized.tz_localize(tz) reset = localized.tz_localize(None) assert reset.tzinfo is None - tm.assert_index_equal(reset, idx) + expected = idx._with_freq(None) + tm.assert_index_equal(reset, expected) def test_dti_tz_localize_naive(self): rng = date_range("1/1/2011", periods=100, freq="H") @@ -466,7 +469,7 @@ def test_dti_tz_localize_naive(self): conv = rng.tz_localize("US/Pacific") exp = date_range("1/1/2011", periods=100, freq="H", tz="US/Pacific") - tm.assert_index_equal(conv, exp) + tm.assert_index_equal(conv, exp._with_freq(None)) def test_dti_tz_localize_tzlocal(self): # GH#13583 @@ -526,8 +529,9 @@ def test_dti_tz_localize_ambiguous_flags(self, tz): di = DatetimeIndex(times) is_dst = [1, 1, 0, 0, 0] localized = di.tz_localize(tz, ambiguous=is_dst) - tm.assert_index_equal(dr, localized) - tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz, ambiguous=is_dst)) + expected = dr._with_freq(None) + tm.assert_index_equal(expected, localized) + tm.assert_index_equal(expected, DatetimeIndex(times, tz=tz, ambiguous=is_dst)) localized = di.tz_localize(tz, ambiguous=np.array(is_dst)) tm.assert_index_equal(dr, localized) @@ -703,9 +707,9 @@ def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, tz_type): def test_normalize_tz(self): rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz="US/Eastern") - result = rng.normalize() + result = rng.normalize() # does not preserve freq expected = date_range("1/1/2000", periods=10, freq="D", tz="US/Eastern") - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected._with_freq(None)) assert result.is_normalized assert not rng.is_normalized @@ -720,9 +724,9 @@ def test_normalize_tz(self): assert not rng.is_normalized rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal()) - result = rng.normalize() + result = rng.normalize() # does not preserve freq expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal()) - tm.assert_index_equal(result, expected) + tm.assert_index_equal(result, expected._with_freq(None)) assert result.is_normalized assert not rng.is_normalized @@ -746,6 +750,7 @@ def test_normalize_tz_local(self, timezone): result = rng.normalize() expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal()) + expected = expected._with_freq(None) tm.assert_index_equal(result, expected) assert result.is_normalized @@ -777,10 +782,8 @@ def test_dti_constructor_with_fixed_tz(self): @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_dti_convert_datetime_list(self, tzstr): dr = date_range("2012-06-02", periods=10, tz=tzstr, name="foo") - dr2 = DatetimeIndex(list(dr), name="foo") + dr2 = DatetimeIndex(list(dr), name="foo", freq="D") tm.assert_index_equal(dr, dr2) - assert dr.tz == dr2.tz - assert dr2.name == "foo" def test_dti_construction_univalent(self): rng = date_range("03/12/2012 00:00", periods=10, freq="W-FRI", tz="US/Eastern") @@ -803,6 +806,7 @@ def test_dti_tz_constructors(self, tzstr): idx1 = to_datetime(arr).tz_localize(tzstr) idx2 = pd.date_range(start="2005-11-10 08:00:00", freq="H", periods=2, tz=tzstr) + idx2 = idx2._with_freq(None) # the others all have freq=None idx3 = DatetimeIndex(arr, tz=tzstr) idx4 = DatetimeIndex(np.array(arr), tz=tzstr) @@ -913,7 +917,7 @@ def test_date_range_localize(self): rng3 = date_range("3/11/2012 03:00", periods=15, freq="H") rng3 = rng3.tz_localize("US/Eastern") - tm.assert_index_equal(rng, rng3) + tm.assert_index_equal(rng._with_freq(None), rng3) # DST transition time val = rng[0] @@ -926,7 +930,9 @@ def test_date_range_localize(self): # Right before the DST transition rng = date_range("3/11/2012 00:00", periods=2, freq="H", tz="US/Eastern") - rng2 = DatetimeIndex(["3/11/2012 00:00", "3/11/2012 01:00"], tz="US/Eastern") + rng2 = DatetimeIndex( + ["3/11/2012 00:00", "3/11/2012 01:00"], tz="US/Eastern", freq="H" + ) tm.assert_index_equal(rng, rng2) exp = Timestamp("3/11/2012 00:00", tz="US/Eastern") assert exp.hour == 0 diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index aa1bf997fc66b..0e5abe2f5ccd1 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -144,7 +144,8 @@ def test_drop_duplicates_metadata(self, freq_sample): idx_dup = idx.append(idx) assert idx_dup.freq is None # freq is reset result = idx_dup.drop_duplicates() - tm.assert_index_equal(idx, result) + expected = idx._with_freq(None) + tm.assert_index_equal(expected, result) assert result.freq is None @pytest.mark.parametrize( diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index c8c2d1ed587cf..17ca23055f6e0 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -145,7 +145,11 @@ def test_indexing_with_datetimeindex_tz(self): for sel in (index, list(index)): # getitem - tm.assert_series_equal(ser[sel], ser) + result = ser[sel] + expected = ser + if sel is not index: + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(result, expected) # setitem result = ser.copy() @@ -154,7 +158,8 @@ def test_indexing_with_datetimeindex_tz(self): tm.assert_series_equal(result, expected) # .loc getitem - tm.assert_series_equal(ser.loc[sel], ser) + result = ser.loc[sel] + tm.assert_series_equal(result, ser) # .loc setitem result = ser.copy() @@ -226,6 +231,7 @@ def test_series_partial_set_datetime(self): result = ser.loc[[Timestamp("2011-01-01"), Timestamp("2011-01-02")]] exp = Series([0.1, 0.2], index=idx, name="s") + exp.index = exp.index._with_freq(None) tm.assert_series_equal(result, exp, check_index_type=True) keys = [ diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 2e691c6fd76d8..6c259db33cf7c 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -119,7 +119,7 @@ def test_partial_setting(self): ) expected = pd.concat( - [df_orig, DataFrame({"A": 7}, index=[dates[-1] + dates.freq])], sort=True + [df_orig, DataFrame({"A": 7}, index=dates[-1:] + dates.freq)], sort=True ) df = df_orig.copy() df.loc[dates[-1] + dates.freq, "A"] = 7 diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 2d4fdfd5a3950..47aa72e298685 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -55,16 +55,18 @@ def test_sort_index_inplace(self, datetime_series): result = random_order.sort_index(ascending=False, inplace=True) assert result is None - tm.assert_series_equal( - random_order, datetime_series.reindex(datetime_series.index[::-1]) - ) + expected = datetime_series.reindex(datetime_series.index[::-1]) + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(random_order, expected) # ascending random_order = datetime_series.reindex(rindex) result = random_order.sort_index(ascending=True, inplace=True) assert result is None - tm.assert_series_equal(random_order, datetime_series) + expected = datetime_series.copy() + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(random_order, expected) def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) diff --git a/pandas/tests/series/methods/test_to_dict.py b/pandas/tests/series/methods/test_to_dict.py index 2fbf3e8d39cf3..47badb0a1bb52 100644 --- a/pandas/tests/series/methods/test_to_dict.py +++ b/pandas/tests/series/methods/test_to_dict.py @@ -12,9 +12,11 @@ class TestSeriesToDict: ) def test_to_dict(self, mapping, datetime_series): # GH#16122 - tm.assert_series_equal( - Series(datetime_series.to_dict(mapping), name="ts"), datetime_series - ) + result = Series(datetime_series.to_dict(mapping), name="ts") + expected = datetime_series.copy() + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(result, expected) + from_method = Series(datetime_series.to_dict(collections.Counter)) from_constructor = Series(collections.Counter(datetime_series.items())) tm.assert_series_equal(from_method, from_constructor) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index dd0bac683c35c..f113d47ec7340 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1505,6 +1505,7 @@ def test_set_index_datetime(self): tz="US/Eastern", ) idx3 = pd.date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo") + idx3._set_freq(None) df = df.set_index(idx1) df = df.set_index(idx2, append=True)
preparing to add a freq check to assert_index_equal
https://api.github.com/repos/pandas-dev/pandas/pulls/33773
2020-04-24T17:58:25Z
2020-04-24T22:00:42Z
2020-04-24T22:00:42Z
2020-04-24T22:17:44Z
[#33770] bug fix to prevent ExtensionArrays from crashing Series.__repr__()
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 823bfc75e4304..7b5f1fb03dd48 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -733,8 +733,8 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`) -- +- Fixed bug where :meth:`Serires.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`) +- Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`). Other diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 59542a8da535e..c7eb3eeedcadf 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1228,7 +1228,11 @@ def _format(x): vals = extract_array(self.values, extract_numpy=True) - is_float_type = lib.map_infer(vals, is_float) & notna(vals) + is_float_type = ( + lib.map_infer(vals, is_float) + # vals may have 2 or more dimensions + & np.all(notna(vals), axis=tuple(range(1, len(vals.shape)))) + ) leading_space = self.leading_space if leading_space is None: leading_space = is_float_type.any() diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index f3c3344992942..c1850826926d8 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2810,6 +2810,63 @@ def test_to_string_multindex_header(self): assert res == exp +class TestGenericArrayFormatter: + def test_1d_array(self): + # GenericArrayFormatter is used on types for which there isn't a dedicated + # formatter. np.bool is one of those types. + obj = fmt.GenericArrayFormatter(np.array([True, False])) + res = obj.get_result() + assert len(res) == 2 + # Results should be right-justified. + assert res[0] == " True" + assert res[1] == " False" + + def test_2d_array(self): + obj = fmt.GenericArrayFormatter(np.array([[True, False], [False, True]])) + res = obj.get_result() + assert len(res) == 2 + assert res[0] == " [True, False]" + assert res[1] == " [False, True]" + + def test_3d_array(self): + obj = fmt.GenericArrayFormatter( + np.array([[[True, True], [False, False]], [[False, True], [True, False]]]) + ) + res = obj.get_result() + assert len(res) == 2 + assert res[0] == " [[True, True], [False, False]]" + assert res[1] == " [[False, True], [True, False]]" + + def test_2d_extension_type(self): + # GH 33770 + + # Define a stub extension type with just enough code to run Series.__repr__() + class DtypeStub(pd.api.extensions.ExtensionDtype): + @property + def type(self): + return np.ndarray + + @property + def name(self): + return "DtypeStub" + + class ExtTypeStub(pd.api.extensions.ExtensionArray): + def __len__(self): + return 2 + + def __getitem__(self, ix): + return [ix == 1, ix == 0] + + @property + def dtype(self): + return DtypeStub() + + series = pd.Series(ExtTypeStub()) + res = repr(series) # This line crashed before #33770 was fixed. + expected = "0 [False True]\n" + "1 [ True False]\n" + "dtype: DtypeStub" + assert res == expected + + def _three_digit_exp(): return f"{1.7e8:.4g}" == "1.7e+008"
- [X] closes #33770 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry This pull request fixes a bug in `GenericArrayFormatter` that caused a crash when rendering arrays of arrays. This problem causes `Series.__repr__()` to fail with certain extension types; see #33770 for more information. The root cause is this line: ``` python 1231 is_float_type = lib.map_infer(vals, is_float) & notna(vals) ``` The call to `notna()` here returns a 2D array if `vals` is a 2D array, while `lib.map_infer(vals, is_float)` returns a 1D array if `vals` is a 2D array. In addition to fixing that line, this PR also adds tests for the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/33771
2020-04-24T17:23:45Z
2020-05-01T20:36:04Z
2020-05-01T20:36:03Z
2020-05-01T20:36:04Z
BUG: Adjust truncate for decreasing index
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index f1a219ad232de..e90030a6cffb1 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -565,6 +565,7 @@ Indexing - Bug in :meth:`DatetimeIndex.insert` and :meth:`TimedeltaIndex.insert` causing index ``freq`` to be lost when setting an element into an empty :class:`Series` (:issue:33573`) - Bug in :meth:`Series.__setitem__` with an :class:`IntervalIndex` and a list-like key of integers (:issue:`33473`) - Bug in :meth:`Series.__getitem__` allowing missing labels with ``np.ndarray``, :class:`Index`, :class:`Series` indexers but not ``list``, these now all raise ``KeyError`` (:issue:`33646`) +- Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` where index was assumed to be monotone increasing (:issue:`33756`) Missing ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c761bd8cb465a..ed421718c400d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9196,6 +9196,9 @@ def truncate( if before > after: raise ValueError(f"Truncate: {after} must be after {before}") + if ax.is_monotonic_decreasing: + before, after = after, before + slicer = [slice(None, None)] * self._AXIS_LEN slicer[axis] = slice(before, after) result = self.loc[tuple(slicer)] diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py index ad86ee1266874..768a5f22fb063 100644 --- a/pandas/tests/frame/methods/test_truncate.py +++ b/pandas/tests/frame/methods/test_truncate.py @@ -87,3 +87,20 @@ def test_truncate_nonsortedindex(self): msg = "truncate requires a sorted index" with pytest.raises(ValueError, match=msg): df.truncate(before=2, after=20, axis=1) + + @pytest.mark.parametrize( + "before, after, indices", + [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])], + ) + @pytest.mark.parametrize("klass", [pd.Int64Index, pd.DatetimeIndex]) + def test_truncate_decreasing_index(self, before, after, indices, klass): + # https://github.com/pandas-dev/pandas/issues/33756 + idx = klass([3, 2, 1, 0]) + if klass is pd.DatetimeIndex: + before = pd.Timestamp(before) if before is not None else None + after = pd.Timestamp(after) if after is not None else None + indices = [pd.Timestamp(i) for i in indices] + values = pd.DataFrame(range(len(idx)), index=idx) + result = values.truncate(before=before, after=after) + expected = values.loc[indices] + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py index c97369b349f56..47947f0287494 100644 --- a/pandas/tests/series/methods/test_truncate.py +++ b/pandas/tests/series/methods/test_truncate.py @@ -80,6 +80,23 @@ def test_truncate_nonsortedindex(self): with pytest.raises(ValueError, match=msg): ts.sort_values(ascending=False).truncate(before="2011-11", after="2011-12") + @pytest.mark.parametrize( + "before, after, indices", + [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])], + ) + @pytest.mark.parametrize("klass", [pd.Int64Index, pd.DatetimeIndex]) + def test_truncate_decreasing_index(self, before, after, indices, klass): + # https://github.com/pandas-dev/pandas/issues/33756 + idx = klass([3, 2, 1, 0]) + if klass is pd.DatetimeIndex: + before = pd.Timestamp(before) if before is not None else None + after = pd.Timestamp(after) if after is not None else None + indices = [pd.Timestamp(i) for i in indices] + values = pd.Series(range(len(idx)), index=idx) + result = values.truncate(before=before, after=after) + expected = values.loc[indices] + tm.assert_series_equal(result, expected) + def test_truncate_datetimeindex_tz(self): # GH 9243 idx = date_range("4/1/2005", "4/30/2005", freq="D", tz="US/Pacific")
- [x] closes #33756 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33769
2020-04-24T17:08:07Z
2020-04-26T21:04:16Z
2020-04-26T21:04:16Z
2020-04-26T21:47:37Z
DOC: data_columns can take bool
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 495dcc5700241..ef058fd0aa074 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2359,7 +2359,7 @@ def to_hdf( min_itemsize: Optional[Union[int, Dict[str, int]]] = None, nan_rep=None, dropna: Optional[bool_t] = None, - data_columns: Optional[List[str]] = None, + data_columns: Optional[Union[bool_t, List[str]]] = None, errors: str = "strict", encoding: str = "UTF-8", ) -> None: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 311d8d0d55341..5845202550326 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -230,7 +230,7 @@ def to_hdf( min_itemsize: Optional[Union[int, Dict[str, int]]] = None, nan_rep=None, dropna: Optional[bool] = None, - data_columns: Optional[List[str]] = None, + data_columns: Optional[Union[bool, List[str]]] = None, errors: str = "strict", encoding: str = "UTF-8", ):
The ``data_columns`` argument of ``df.to_hdf`` can take ``True`` as an argument, meaning "all columns", yet the type hint is ``Optional[List[str]]``, triggering warnings in e.g. pyCharm. - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33768
2020-04-24T16:37:52Z
2020-04-24T18:08:24Z
2020-04-24T18:08:24Z
2022-04-30T19:47:45Z
BUG: Fix missing tick labels on twinned axes
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 18940b574b517..9a597c134a10a 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -331,6 +331,7 @@ Plotting - Bug in :meth:`DataFrame.plot` was rotating xticklabels when ``subplots=True``, even if the x-axis wasn't an irregular time series (:issue:`29460`) - Bug in :meth:`DataFrame.plot` where a marker letter in the ``style`` keyword sometimes causes a ``ValueError`` (:issue:`21003`) +- Twinned axes were losing their tick labels which should only happen to all but the last row or column of 'externally' shared axes (:issue:`33819`) Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index c5b44f37150bb..aed0c360fc7ce 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -297,6 +297,56 @@ def _remove_labels_from_axis(axis: "Axis"): axis.get_label().set_visible(False) +def _has_externally_shared_axis(ax1: "matplotlib.axes", compare_axis: "str") -> bool: + """ + Return whether an axis is externally shared. + + Parameters + ---------- + ax1 : matplotlib.axes + Axis to query. + compare_axis : str + `"x"` or `"y"` according to whether the X-axis or Y-axis is being + compared. + + Returns + ------- + bool + `True` if the axis is externally shared. Otherwise `False`. + + Notes + ----- + If two axes with different positions are sharing an axis, they can be + referred to as *externally* sharing the common axis. + + If two axes sharing an axis also have the same position, they can be + referred to as *internally* sharing the common axis (a.k.a twinning). + + _handle_shared_axes() is only interested in axes externally sharing an + axis, regardless of whether either of the axes is also internally sharing + with a third axis. + """ + if compare_axis == "x": + axes = ax1.get_shared_x_axes() + elif compare_axis == "y": + axes = ax1.get_shared_y_axes() + else: + raise ValueError( + "_has_externally_shared_axis() needs 'x' or 'y' as a second parameter" + ) + + axes = axes.get_siblings(ax1) + + # Retain ax1 and any of its siblings which aren't in the same position as it + ax1_points = ax1.get_position().get_points() + + for ax2 in axes: + if not np.array_equal(ax1_points, ax2.get_position().get_points()): + return True + + return False + + def handle_shared_axes( axarr: Iterable["Axes"], nplots: int, @@ -328,7 +378,7 @@ def handle_shared_axes( # the last in the column, because below is no subplot/gap. if not layout[row_num(ax) + 1, col_num(ax)]: continue - if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1: + if sharex or _has_externally_shared_axis(ax, "x"): _remove_labels_from_axis(ax.xaxis) except IndexError: @@ -337,7 +387,7 @@ def handle_shared_axes( for ax in axarr: if ax.is_last_row(): continue - if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1: + if sharex or _has_externally_shared_axis(ax, "x"): _remove_labels_from_axis(ax.xaxis) if ncols > 1: @@ -347,7 +397,7 @@ def handle_shared_axes( # have a subplot there, we can skip the layout test if ax.is_first_col(): continue - if sharey or len(ax.get_shared_y_axes().get_siblings(ax)) > 1: + if sharey or _has_externally_shared_axis(ax, "y"): _remove_labels_from_axis(ax.yaxis) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 0208ab3e0225b..2838bef2a10b0 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -433,3 +433,117 @@ def test_dictionary_color(self): ax = df1.plot(kind="line", color=dic_color) colors = [rect.get_color() for rect in ax.get_lines()[0:2]] assert all(color == expected[index] for index, color in enumerate(colors)) + + @pytest.mark.slow + def test_has_externally_shared_axis_x_axis(self): + # GH33819 + # Test _has_externally_shared_axis() works for x-axis + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = self.plt.figure() + plots = fig.subplots(2, 4) + + # Create *externally* shared axes for first and third columns + plots[0][0] = fig.add_subplot(231, sharex=plots[1][0]) + plots[0][2] = fig.add_subplot(233, sharex=plots[1][2]) + + # Create *internally* shared axes for second and third columns + plots[0][1].twinx() + plots[0][2].twinx() + + # First column is only externally shared + # Second column is only internally shared + # Third column is both + # Fourth column is neither + assert func(plots[0][0], "x") + assert not func(plots[0][1], "x") + assert func(plots[0][2], "x") + assert not func(plots[0][3], "x") + + @pytest.mark.slow + def test_has_externally_shared_axis_y_axis(self): + # GH33819 + # Test _has_externally_shared_axis() works for y-axis + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = self.plt.figure() + plots = fig.subplots(4, 2) + + # Create *externally* shared axes for first and third rows + plots[0][0] = fig.add_subplot(321, sharey=plots[0][1]) + plots[2][0] = fig.add_subplot(325, sharey=plots[2][1]) + + # Create *internally* shared axes for second and third rows + plots[1][0].twiny() + plots[2][0].twiny() + + # First row is only externally shared + # Second row is only internally shared + # Third row is both + # Fourth row is neither + assert func(plots[0][0], "y") + assert not func(plots[1][0], "y") + assert func(plots[2][0], "y") + assert not func(plots[3][0], "y") + + @pytest.mark.slow + def test_has_externally_shared_axis_invalid_compare_axis(self): + # GH33819 + # Test _has_externally_shared_axis() raises an exception when + # passed an invalid value as compare_axis parameter + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = self.plt.figure() + plots = fig.subplots(4, 2) + + # Create arbitrary axes + plots[0][0] = fig.add_subplot(321, sharey=plots[0][1]) + + # Check that an invalid compare_axis value triggers the expected exception + msg = "needs 'x' or 'y' as a second parameter" + with pytest.raises(ValueError, match=msg): + func(plots[0][0], "z") + + @pytest.mark.slow + def test_externally_shared_axes(self): + # Example from GH33819 + # Create data + df = DataFrame({"a": np.random.randn(1000), "b": np.random.randn(1000)}) + + # Create figure + fig = self.plt.figure() + plots = fig.subplots(2, 3) + + # Create *externally* shared axes + plots[0][0] = fig.add_subplot(231, sharex=plots[1][0]) + # note: no plots[0][1] that's the twin only case + plots[0][2] = fig.add_subplot(233, sharex=plots[1][2]) + + # Create *internally* shared axes + # note: no plots[0][0] that's the external only case + twin_ax1 = plots[0][1].twinx() + twin_ax2 = plots[0][2].twinx() + + # Plot data to primary axes + df["a"].plot(ax=plots[0][0], title="External share only").set_xlabel( + "this label should never be visible" + ) + df["a"].plot(ax=plots[1][0]) + + df["a"].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel( + "this label should always be visible" + ) + df["a"].plot(ax=plots[1][1]) + + df["a"].plot(ax=plots[0][2], title="Both").set_xlabel( + "this label should never be visible" + ) + df["a"].plot(ax=plots[1][2]) + + # Plot data to twinned axes + df["b"].plot(ax=twin_ax1, color="green") + df["b"].plot(ax=twin_ax2, color="yellow") + + assert not plots[0][0].xaxis.get_label().get_visible() + assert plots[0][1].xaxis.get_label().get_visible() + assert not plots[0][2].xaxis.get_label().get_visible()
## Background: Multi-row and/or multi-column subplots can utilize shared axes. An external share happens at axis creation when a sharex or sharey parameter is specified. An internal share, or twinning, occurs when an overlayed axis is created by the Axes.twinx() or Axes.twiny() calls. The two types of sharing can be distinguished after the fact in the following manner. If two axes sharing an axis also have the same position, they are not in an external axis share, they are twinned. For externally shared axes Pandas automatically removes tick labels for all but the last row and/or first column in ./pandas/plotting/_matplotlib/tools.py's function _handle_shared_axes(). ## The problem: _handle_shared_axes() should be interested in externally shared axes, whether or not they are also twinned. It should, but doesn't, ignore axes which are only twinned. Which means that twinned-only axes wrongly lose their tick labels. ## The cure: This commit introduces _has_externally_shared_axis() which identifies externally shared axes and uses it to expand upon the existing use of len(Axes.get_shared_{x,y}_axes().get_siblings(a{x,y})) in _handle_shared_axes() which miss these cases. ## The demonstration test case: Note especially the axis labels (and associated tick labels). ```python #!/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np import pandas as pd # Create data df = pd.DataFrame({'a': np.random.randn(1000), 'b': np.random.randn(1000)}) # Create figure fig = plt.figure() plots = fig.subplots(2, 3) # Create *externally* shared axes plots[0][0] = plt.subplot(231, sharex=plots[1][0]) # note: no plots[0][1] that's the twin only case plots[0][2] = plt.subplot(233, sharex=plots[1][2]) # Create *internally* shared axes # note: no plots[0][0] that's the external only case twin_ax1 = plots[0][1].twinx() twin_ax2 = plots[0][2].twinx() # Plot data to primary axes df['a'].plot(ax=plots[0][0], title="External share only").set_xlabel("this label should never be visible") df['a'].plot(ax=plots[1][0]) df['a'].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel("this label should always be visible") df['a'].plot(ax=plots[1][1]) df['a'].plot(ax=plots[0][2], title="Both").set_xlabel("this label should never be visible") df['a'].plot(ax=plots[1][2]) # Plot data to twinned axes df['b'].plot(ax=twin_ax1, color='green') df['b'].plot(ax=twin_ax2, color='yellow') # Do it plt.show() ``` See images produced by this code for problem and fixed cases at the bug report: #33819. - [x] closes #33819 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33767
2020-04-24T16:20:26Z
2020-09-30T00:11:53Z
2020-09-30T00:11:52Z
2020-09-30T07:30:48Z
REF: simplify _try_cast
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index d1b07585943ea..2f71f4f4ccc19 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -27,7 +27,6 @@ maybe_upcast, ) from pandas.core.dtypes.common import ( - is_categorical_dtype, is_datetime64_ns_dtype, is_extension_array_dtype, is_float_dtype, @@ -37,7 +36,7 @@ is_object_dtype, is_timedelta64_ns_dtype, ) -from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, registry +from pandas.core.dtypes.dtypes import ExtensionDtype, registry from pandas.core.dtypes.generic import ( ABCExtensionArray, ABCIndexClass, @@ -529,13 +528,23 @@ def _try_cast( if maybe_castable(arr) and not copy and dtype is None: return arr + if isinstance(dtype, ExtensionDtype) and dtype.kind != "M": + # create an extension array from its dtype + # DatetimeTZ case needs to go through maybe_cast_to_datetime + array_type = dtype.construct_array_type()._from_sequence + subarr = array_type(arr, dtype=dtype, copy=copy) + return subarr + try: # GH#15832: Check if we are requesting a numeric dype and # that we can convert the data to the requested dtype. if is_integer_dtype(dtype): - subarr = maybe_cast_to_integer_array(arr, dtype) + # this will raise if we have e.g. floats + maybe_cast_to_integer_array(arr, dtype) + subarr = arr + else: + subarr = maybe_cast_to_datetime(arr, dtype) - subarr = maybe_cast_to_datetime(arr, dtype) # Take care in creating object arrays (but iterators are not # supported): if is_object_dtype(dtype) and ( @@ -549,19 +558,7 @@ def _try_cast( # in case of out of bound datetime64 -> always raise raise except (ValueError, TypeError): - if is_categorical_dtype(dtype): - # We *do* allow casting to categorical, since we know - # that Categorical is the only array type for 'category'. - dtype = cast(CategoricalDtype, dtype) - subarr = dtype.construct_array_type()( - arr, dtype.categories, ordered=dtype.ordered - ) - elif is_extension_array_dtype(dtype): - # create an extension array from its dtype - dtype = cast(ExtensionDtype, dtype) - array_type = dtype.construct_array_type()._from_sequence - subarr = array_type(arr, dtype=dtype, copy=copy) - elif dtype is not None and raise_cast_failure: + if dtype is not None and raise_cast_failure: raise else: subarr = np.array(arr, dtype=object, copy=copy)
Part of a sequence of PRs aimed at sharing code between Series/Index/array
https://api.github.com/repos/pandas-dev/pandas/pulls/33764
2020-04-24T14:48:10Z
2020-04-24T21:34:25Z
2020-04-24T21:34:25Z
2020-04-24T22:21:12Z
TYP/CLN: rogue type comment not caught by code checks
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index ccc970fb453c2..260cc69187d38 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -157,7 +157,7 @@ def validate_argsort_with_ascending(ascending, args, kwargs): return ascending -CLIP_DEFAULTS = dict(out=None) # type Dict[str, Any] +CLIP_DEFAULTS: Dict[str, Any] = dict(out=None) validate_clip = CompatValidator( CLIP_DEFAULTS, fname="clip", method="both", max_fname_arg_count=3 )
https://api.github.com/repos/pandas-dev/pandas/pulls/33763
2020-04-24T14:38:53Z
2020-04-24T15:26:48Z
2020-04-24T15:26:48Z
2020-04-24T15:38:30Z
REGR: fix DataFrame reduction with EA columns and numeric_only=True
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7ad7e8f5a27b0..f8199524abbaf 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -571,6 +571,7 @@ Numeric - Bug in :meth:`DataFrame.mean` with ``numeric_only=False`` and either ``datetime64`` dtype or ``PeriodDtype`` column incorrectly raising ``TypeError`` (:issue:`32426`) - Bug in :meth:`DataFrame.count` with ``level="foo"`` and index level ``"foo"`` containing NaNs causes segmentation fault (:issue:`21824`) - Bug in :meth:`DataFrame.diff` with ``axis=1`` returning incorrect results with mixed dtypes (:issue:`32995`) +- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`). - Bug in :meth:`DataFrame.corr` and :meth:`DataFrame.cov` raising when handling nullable integer columns with ``pandas.NA`` (:issue:`33803`) - Bug in :class:`DataFrame` and :class:`Series` addition and subtraction between object-dtype objects and ``datetime64`` dtype objects (:issue:`33824`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f8cb99e2b2e75..3d563f48d32c9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8325,10 +8325,10 @@ def _get_data(axis_matters): out_dtype = "bool" if filter_type == "bool" else None def blk_func(values): - if values.ndim == 1 and not isinstance(values, np.ndarray): - # we can't pass axis=1 - return op(values, axis=0, skipna=skipna, **kwds) - return op(values, axis=1, skipna=skipna, **kwds) + if isinstance(values, ExtensionArray): + return values._reduce(name, skipna=skipna, **kwds) + else: + return op(values, axis=1, skipna=skipna, **kwds) # After possibly _get_data and transposing, we are now in the # simple case where we can use BlockManager._reduce diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 75afc59382a75..f69c85c070ca4 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -896,9 +896,17 @@ def test_mean_datetimelike_numeric_only_false(self): # mean of period is not allowed df["D"] = pd.period_range("2016", periods=3, freq="A") - with pytest.raises(TypeError, match="reduction operation 'mean' not allowed"): + with pytest.raises(TypeError, match="mean is not implemented for Period"): df.mean(numeric_only=False) + def test_mean_extensionarray_numeric_only_true(self): + # https://github.com/pandas-dev/pandas/issues/33256 + arr = np.random.randint(1000, size=(10, 5)) + df = pd.DataFrame(arr, dtype="Int64") + result = df.mean(numeric_only=True) + expected = pd.DataFrame(arr).mean() + tm.assert_series_equal(result, expected) + def test_stats_mixed_type(self, float_string_frame): # don't blow up float_string_frame.std(1)
Closes #33256 For the block-wise path in `DataFrame._reduce`, we ensure to use the EA reduction for blocks holding EAs, instead of passing the EA to the `op` function (which is typically the `nanops` nan function). This needs https://github.com/pandas-dev/pandas/pull/33758 to be merged, since that PR fixes the test that is failing here.
https://api.github.com/repos/pandas-dev/pandas/pulls/33761
2020-04-24T09:39:35Z
2020-05-01T18:19:12Z
2020-05-01T18:19:11Z
2020-05-26T09:36:02Z
REGR: disallow mean of period column again
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2d2f7bbf7092f..0eda80a78ee4f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -100,7 +100,6 @@ is_list_like, is_named_tuple, is_object_dtype, - is_period_dtype, is_scalar, is_sequence, needs_i8_conversion, @@ -8225,7 +8224,7 @@ def _reduce( dtype_is_dt = np.array( [ - is_datetime64_any_dtype(values.dtype) or is_period_dtype(values.dtype) + is_datetime64_any_dtype(values.dtype) for values in self._iter_column_arrays() ], dtype=bool, @@ -8233,7 +8232,7 @@ def _reduce( if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any(): warnings.warn( "DataFrame.mean and DataFrame.median with numeric_only=None " - "will include datetime64, datetime64tz, and PeriodDtype columns in a " + "will include datetime64 and datetime64tz columns in a " "future version.", FutureWarning, stacklevel=3, diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index b9ff0a5959c01..32b05872ded3f 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -7,7 +7,7 @@ from pandas._config import get_option -from pandas._libs import NaT, Period, Timedelta, Timestamp, iNaT, lib +from pandas._libs import NaT, Timedelta, Timestamp, iNaT, lib from pandas._typing import ArrayLike, Dtype, Scalar from pandas.compat._optional import import_optional_dependency @@ -353,14 +353,6 @@ def _wrap_results(result, dtype: Dtype, fill_value=None): else: result = result.astype("m8[ns]").view(dtype) - elif isinstance(dtype, PeriodDtype): - if is_float(result) and result.is_integer(): - result = int(result) - if is_integer(result): - result = Period._from_ordinal(result, freq=dtype.freq) - else: - raise NotImplementedError(type(result), result) - return result @@ -516,6 +508,7 @@ def nansum( return _wrap_results(the_sum, dtype) +@disallow(PeriodDtype) @bottleneck_switch() def nanmean(values, axis=None, skipna=True, mask=None): """ @@ -547,7 +540,12 @@ def nanmean(values, axis=None, skipna=True, mask=None): ) dtype_sum = dtype_max dtype_count = np.float64 - if is_integer_dtype(dtype) or needs_i8_conversion(dtype): + # not using needs_i8_conversion because that includes period + if ( + is_integer_dtype(dtype) + or is_datetime64_any_dtype(dtype) + or is_timedelta64_dtype(dtype) + ): dtype_sum = np.float64 elif is_float_dtype(dtype): dtype_sum = dtype diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 0255759513e28..75afc59382a75 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -885,16 +885,20 @@ def test_mean_datetimelike_numeric_only_false(self): "A": np.arange(3), "B": pd.date_range("2016-01-01", periods=3), "C": pd.timedelta_range("1D", periods=3), - "D": pd.period_range("2016", periods=3, freq="A"), } ) + # datetime(tz) and timedelta work result = df.mean(numeric_only=False) - expected = pd.Series( - {"A": 1, "B": df.loc[1, "B"], "C": df.loc[1, "C"], "D": df.loc[1, "D"]} - ) + expected = pd.Series({"A": 1, "B": df.loc[1, "B"], "C": df.loc[1, "C"]}) tm.assert_series_equal(result, expected) + # mean of period is not allowed + df["D"] = pd.period_range("2016", periods=3, freq="A") + + with pytest.raises(TypeError, match="reduction operation 'mean' not allowed"): + df.mean(numeric_only=False) + def test_stats_mixed_type(self, float_string_frame): # don't blow up float_string_frame.std(1)
This reverts parts of https://github.com/pandas-dev/pandas/pull/32426 and https://github.com/pandas-dev/pandas/pull/29941 (those are only on master, not yet released), to disallow taking the mean on a Period dtype column again. The mean for period is not supported on PeriodArray itself or for a Series of period dtype (on purpose, see discussion in https://github.com/pandas-dev/pandas/pull/24757 when mean for datetimelike was added), so for DataFrame columns it should also not work. See also comment at https://github.com/pandas-dev/pandas/pull/32426#issuecomment-618872954 cc @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/33758
2020-04-24T09:20:59Z
2020-04-24T21:35:45Z
2020-04-24T21:35:45Z
2020-04-25T11:46:15Z
BUG: MonthOffset.name
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 495dcc5700241..3adae989af58a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -104,6 +104,7 @@ from pandas.io.formats.format import DataFrameFormatter, format_percentiles from pandas.io.formats.printing import pprint_thing from pandas.tseries.frequencies import to_offset +from pandas.tseries.offsets import Tick if TYPE_CHECKING: from pandas.core.resample import Resampler @@ -8068,7 +8069,7 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries: end_date = end = self.index[0] + offset # Tick-like, e.g. 3 weeks - if not offset.is_anchored() and hasattr(offset, "_inc"): + if isinstance(offset, Tick): if end_date in self.index: end = self.index.searchsorted(end_date, side="left") return self.iloc[:end] diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 044dfa703c081..0a7eaa7b7be3e 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -4315,6 +4315,13 @@ def test_valid_month_attributes(kwd, month_classes): cls(**{kwd: 3}) +def test_month_offset_name(month_classes): + # GH#33757 off.name with n != 1 should not raise AttributeError + obj = month_classes(1) + obj2 = month_classes(2) + assert obj2.name == obj.name + + @pytest.mark.parametrize("kwd", sorted(liboffsets.relativedelta_kwds)) def test_valid_relativedelta_kwargs(kwd): # Check that all the arguments specified in liboffsets.relativedelta_kwds diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 8ba10f56f163c..effd923cedd17 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1125,14 +1125,6 @@ class MonthOffset(SingleConstructorOffset): __init__ = BaseOffset.__init__ - @property - def name(self) -> str: - if self.is_anchored: - return self.rule_code - else: - month = ccalendar.MONTH_ALIASES[self.n] - return f"{self.code_rule}-{month}" - def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry `is_anchored` is being accessed indirectly (its not a property). As a result we never go down the other path, which would raise AttributeError since there is no `code_rule`.
https://api.github.com/repos/pandas-dev/pandas/pulls/33757
2020-04-24T02:38:17Z
2020-04-25T00:30:01Z
2020-04-25T00:30:01Z
2020-04-25T00:39:36Z
CI: Revert Cython Pin (take 2)
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 17c3d318ce54d..29ebfe2639e32 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -14,8 +14,7 @@ dependencies: - pytz - pip - pip: - - cython==0.29.16 - # GH#33507 cython 3.0a1 is causing TypeErrors 2020-04-13 + - cython>=0.29.16 - "git+git://github.com/dateutil/dateutil.git" - "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com" - "--pre"
- [x] closes #33507 reverts #33534 New Cython pre release available today - https://pypi.org/project/Cython/3.0a2/ cc @WillAyd Update: 3.0a2 (no such luck - seems there is a regression which is being looked at) https://mail.python.org/pipermail/cython-devel/2020-April/005340.html https://github.com/cython/cython/issues/3544 Update now trying 3.0a3
https://api.github.com/repos/pandas-dev/pandas/pulls/33755
2020-04-23T22:49:55Z
2020-04-27T23:10:34Z
2020-04-27T23:10:34Z
2020-04-27T23:47:08Z
CLN: Parametrize dtype inference tests
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 8c0580b7cf047..8b20f9ada8ff7 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -354,71 +354,69 @@ def test_is_recompilable_fails(ll): class TestInference: - def test_infer_dtype_bytes(self): - compare = "bytes" - - # string array of bytes - arr = np.array(list("abc"), dtype="S1") - assert lib.infer_dtype(arr, skipna=True) == compare + @pytest.mark.parametrize( + "arr", + [ + np.array(list("abc"), dtype="S1"), + np.array(list("abc"), dtype="S1").astype(object), + [b"a", np.nan, b"c"], + ], + ) + def test_infer_dtype_bytes(self, arr): + result = lib.infer_dtype(arr, skipna=True) + assert result == "bytes" - # object array of bytes - arr = arr.astype(object) - assert lib.infer_dtype(arr, skipna=True) == compare + @pytest.mark.parametrize( + "value, expected", + [ + (float("inf"), True), + (np.inf, True), + (-np.inf, False), + (1, False), + ("a", False), + ], + ) + def test_isposinf_scalar(self, value, expected): + # GH 11352 + result = libmissing.isposinf_scalar(value) + assert result is expected - # object array of bytes with missing values - assert lib.infer_dtype([b"a", np.nan, b"c"], skipna=True) == compare + @pytest.mark.parametrize( + "value, expected", + [ + (float("-inf"), True), + (-np.inf, True), + (np.inf, False), + (1, False), + ("a", False), + ], + ) + def test_isneginf_scalar(self, value, expected): + result = libmissing.isneginf_scalar(value) + assert result is expected - def test_isinf_scalar(self): - # GH 11352 - assert libmissing.isposinf_scalar(float("inf")) - assert libmissing.isposinf_scalar(np.inf) - assert not libmissing.isposinf_scalar(-np.inf) - assert not libmissing.isposinf_scalar(1) - assert not libmissing.isposinf_scalar("a") - - assert libmissing.isneginf_scalar(float("-inf")) - assert libmissing.isneginf_scalar(-np.inf) - assert not libmissing.isneginf_scalar(np.inf) - assert not libmissing.isneginf_scalar(1) - assert not libmissing.isneginf_scalar("a") - - @pytest.mark.parametrize("maybe_int", [True, False]) + @pytest.mark.parametrize("coerce_numeric", [True, False]) @pytest.mark.parametrize( "infinity", ["inf", "inF", "iNf", "Inf", "iNF", "InF", "INf", "INF"] ) - def test_maybe_convert_numeric_infinities(self, infinity, maybe_int): + @pytest.mark.parametrize("prefix", ["", "-", "+"]) + def test_maybe_convert_numeric_infinities(self, coerce_numeric, infinity, prefix): # see gh-13274 - na_values = {"", "NULL", "nan"} - - pos = np.array(["inf"], dtype=np.float64) - neg = np.array(["-inf"], dtype=np.float64) - - msg = "Unable to parse string" - - out = lib.maybe_convert_numeric( - np.array([infinity], dtype=object), na_values, maybe_int - ) - tm.assert_numpy_array_equal(out, pos) - - out = lib.maybe_convert_numeric( - np.array(["-" + infinity], dtype=object), na_values, maybe_int - ) - tm.assert_numpy_array_equal(out, neg) - - out = lib.maybe_convert_numeric( - np.array([infinity], dtype=object), na_values, maybe_int - ) - tm.assert_numpy_array_equal(out, pos) - - out = lib.maybe_convert_numeric( - np.array(["+" + infinity], dtype=object), na_values, maybe_int + result = lib.maybe_convert_numeric( + np.array([prefix + infinity], dtype=object), + na_values={"", "NULL", "nan"}, + coerce_numeric=coerce_numeric, ) - tm.assert_numpy_array_equal(out, pos) + expected = np.array([np.inf if prefix in ["", "+"] else -np.inf]) + tm.assert_numpy_array_equal(result, expected) - # too many characters + def test_maybe_convert_numeric_infinities_raises(self): + msg = "Unable to parse string" with pytest.raises(ValueError, match=msg): lib.maybe_convert_numeric( - np.array(["foo_" + infinity], dtype=object), na_values, maybe_int + np.array(["foo_inf"], dtype=object), + na_values={"", "NULL", "nan"}, + coerce_numeric=False, ) def test_maybe_convert_numeric_post_floatify_nan(self, coerce):
https://api.github.com/repos/pandas-dev/pandas/pulls/33753
2020-04-23T21:11:22Z
2020-04-23T22:38:15Z
2020-04-23T22:38:15Z
2020-04-23T22:39:28Z
TST: pd.NA TypeError in drop_duplicates with object dtype
diff --git a/pandas/conftest.py b/pandas/conftest.py index 70be6b5d9fcbc..0adbaf6a112cf 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -256,7 +256,9 @@ def nselect_method(request): # ---------------------------------------------------------------- # Missing values & co. # ---------------------------------------------------------------- -@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN"), pd.NA]) +@pytest.fixture( + params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN"), pd.NA], ids=str +) def nulls_fixture(request): """ Fixture for each null type in pandas. diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index fd4bae26ade57..7c6391140e2bb 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -418,3 +418,10 @@ def test_drop_duplicates_ignore_index( tm.assert_frame_equal(result_df, expected) tm.assert_frame_equal(df, DataFrame(origin_dict)) + + +def test_drop_duplicates_null_in_object_column(nulls_fixture): + # https://github.com/pandas-dev/pandas/issues/32992 + df = DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object) + result = df.drop_duplicates() + tm.assert_frame_equal(result, df)
- [ ] closes #32992 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33751
2020-04-23T19:49:07Z
2020-04-24T22:25:24Z
2020-04-24T22:25:23Z
2020-04-25T09:14:57Z
CLN: Remove is_null_period
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index bbb4d562b8971..a312fdc6cda22 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -67,7 +67,11 @@ cimport pandas._libs.util as util from pandas._libs.util cimport is_nan, UINT64_MAX, INT64_MAX, INT64_MIN from pandas._libs.tslib import array_to_datetime -from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT +from pandas._libs.tslibs.nattype cimport ( + NPY_NAT, + c_NaT as NaT, + checknull_with_nat, +) from pandas._libs.tslibs.conversion cimport convert_to_tsobject from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64 from pandas._libs.tslibs.timezones cimport get_timezone, tz_compare @@ -77,7 +81,6 @@ from pandas._libs.missing cimport ( isnaobj, is_null_datetime64, is_null_timedelta64, - is_null_period, C_NA, ) @@ -1844,7 +1847,7 @@ cdef class PeriodValidator(TemporalValidator): return util.is_period_object(value) cdef inline bint is_valid_null(self, object value) except -1: - return is_null_period(value) + return checknull_with_nat(value) cpdef bint is_period_array(ndarray values): diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd index 5ab42a736712f..b32492c1a83fc 100644 --- a/pandas/_libs/missing.pxd +++ b/pandas/_libs/missing.pxd @@ -6,7 +6,6 @@ cpdef ndarray[uint8_t] isnaobj(ndarray arr) cdef bint is_null_datetime64(v) cdef bint is_null_timedelta64(v) -cdef bint is_null_period(v) cdef class C_NAType: pass diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index dacf454824190..490abdf473319 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -40,6 +40,7 @@ cpdef bint checknull(object val): - NaT - np.datetime64 representation of NaT - np.timedelta64 representation of NaT + - NA Parameters ---------- @@ -278,12 +279,6 @@ cdef inline bint is_null_timedelta64(v): return False -cdef inline bint is_null_period(v): - # determine if we have a null for a Period (or integer versions), - # excluding np.datetime64('nat') and np.timedelta64('nat') - return checknull_with_nat(v) - - # ----------------------------------------------------------------------------- # Implementation of NA singleton
is_null_period seems only to be an alias for checknull_with_nat so I think it can be removed?
https://api.github.com/repos/pandas-dev/pandas/pulls/33750
2020-04-23T17:18:22Z
2020-04-23T18:56:18Z
2020-04-23T18:56:18Z
2020-04-23T18:58:56Z
BUG: Fix mixed datetime dtype inference
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 88bf0e005a221..16426e11c5a24 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -759,6 +759,7 @@ Datetimelike - Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`) - Bug in :meth:`DatetimeIndex.tz_localize` incorrectly retaining ``freq`` in some cases where the original freq is no longer valid (:issue:`30511`) - Bug in :meth:`DatetimeIndex.intersection` losing ``freq`` and timezone in some cases (:issue:`33604`) +- Bug in :meth:`DatetimeIndex.get_indexer` where incorrect output would be returned for mixed datetime-like targets (:issue:`33741`) - Bug in :class:`DatetimeIndex` addition and subtraction with some types of :class:`DateOffset` objects incorrectly retaining an invalid ``freq`` attribute (:issue:`33779`) - Bug in :class:`DatetimeIndex` where setting the ``freq`` attribute on an index could silently change the ``freq`` attribute on another index viewing the same data (:issue:`33552`) - :meth:`DataFrame.min`/:meth:`DataFrame.max` not returning consistent result with :meth:`Series.min`/:meth:`Series.max` when called on objects initialized with empty :func:`pd.to_datetime` diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 222b7af4e4b1c..ea97bab2198eb 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1380,8 +1380,10 @@ def infer_dtype(value: object, skipna: bool = True) -> str: return "mixed-integer" elif PyDateTime_Check(val): - if is_datetime_array(values): + if is_datetime_array(values, skipna=skipna): return "datetime" + elif is_date_array(values, skipna=skipna): + return "date" elif PyDate_Check(val): if is_date_array(values, skipna=skipna): @@ -1752,10 +1754,10 @@ cdef class DatetimeValidator(TemporalValidator): return is_null_datetime64(value) -cpdef bint is_datetime_array(ndarray values): +cpdef bint is_datetime_array(ndarray values, bint skipna=True): cdef: DatetimeValidator validator = DatetimeValidator(len(values), - skipna=True) + skipna=skipna) return validator.validate(values) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index fb266b4abba51..746fd140e48a1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4701,7 +4701,10 @@ def _maybe_promote(self, other: "Index"): """ if self.inferred_type == "date" and isinstance(other, ABCDatetimeIndex): - return type(other)(self), other + try: + return type(other)(self), other + except OutOfBoundsDatetime: + return self, other elif self.inferred_type == "timedelta" and isinstance(other, ABCTimedeltaIndex): # TODO: we dont have tests that get here return type(other)(self), other diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 4c4a5547247fc..e97716f7a5e9c 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1106,6 +1106,21 @@ def test_date(self): result = lib.infer_dtype(dates, skipna=True) assert result == "date" + @pytest.mark.parametrize( + "values", + [ + [date(2020, 1, 1), pd.Timestamp("2020-01-01")], + [pd.Timestamp("2020-01-01"), date(2020, 1, 1)], + [date(2020, 1, 1), pd.NaT], + [pd.NaT, date(2020, 1, 1)], + ], + ) + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype_date_order_invariant(self, values, skipna): + # https://github.com/pandas-dev/pandas/issues/33741 + result = lib.infer_dtype(values, skipna=skipna) + assert result == "date" + def test_is_numeric_array(self): assert lib.is_float_array(np.array([1, 2.0])) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 097ee20534e4e..f08472fe72631 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -1,4 +1,4 @@ -from datetime import datetime, time, timedelta +from datetime import date, datetime, time, timedelta import numpy as np import pytest @@ -575,6 +575,38 @@ def test_get_indexer(self): with pytest.raises(ValueError, match="abbreviation w/o a number"): idx.get_indexer(idx[[0]], method="nearest", tolerance="foo") + @pytest.mark.parametrize( + "target", + [ + [date(2020, 1, 1), pd.Timestamp("2020-01-02")], + [pd.Timestamp("2020-01-01"), date(2020, 1, 2)], + ], + ) + def test_get_indexer_mixed_dtypes(self, target): + # https://github.com/pandas-dev/pandas/issues/33741 + values = pd.DatetimeIndex( + [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] + ) + result = values.get_indexer(target) + expected = np.array([0, 1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "target, positions", + [ + ([date(9999, 1, 1), pd.Timestamp("2020-01-01")], [-1, 0]), + ([pd.Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]), + ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), + ], + ) + def test_get_indexer_out_of_bounds_date(self, target, positions): + values = pd.DatetimeIndex( + [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] + ) + result = values.get_indexer(target) + expected = np.array(positions, dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + class TestMaybeCastSliceBound: def test_maybe_cast_slice_bounds_empty(self):
- [x] closes #33741 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33749
2020-04-23T17:16:03Z
2020-06-01T00:28:41Z
2020-06-01T00:28:41Z
2020-06-01T00:29:55Z
BUG: support skew function for custom BaseIndexer rolling windows
diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst index d7d025981f2f4..f9c07df956341 100644 --- a/doc/source/user_guide/computation.rst +++ b/doc/source/user_guide/computation.rst @@ -318,8 +318,8 @@ We provide a number of common statistical functions: :meth:`~Rolling.kurt`, Sample kurtosis (4th moment) :meth:`~Rolling.quantile`, Sample quantile (value at %) :meth:`~Rolling.apply`, Generic apply - :meth:`~Rolling.cov`, Unbiased covariance (binary) - :meth:`~Rolling.corr`, Correlation (binary) + :meth:`~Rolling.cov`, Sample covariance (binary) + :meth:`~Rolling.corr`, Sample correlation (binary) .. _computation.window_variance.caveats: @@ -341,6 +341,8 @@ We provide a number of common statistical functions: sample variance under the circumstances would result in a biased estimator of the variable we are trying to determine. + The same caveats apply to using any supported statistical sample methods. + .. _stats.rolling_apply: Rolling apply @@ -870,12 +872,12 @@ Method summary :meth:`~Expanding.max`, Maximum :meth:`~Expanding.std`, Sample standard deviation :meth:`~Expanding.var`, Sample variance - :meth:`~Expanding.skew`, Unbiased skewness (3rd moment) - :meth:`~Expanding.kurt`, Unbiased kurtosis (4th moment) + :meth:`~Expanding.skew`, Sample skewness (3rd moment) + :meth:`~Expanding.kurt`, Sample kurtosis (4th moment) :meth:`~Expanding.quantile`, Sample quantile (value at %) :meth:`~Expanding.apply`, Generic apply - :meth:`~Expanding.cov`, Unbiased covariance (binary) - :meth:`~Expanding.corr`, Correlation (binary) + :meth:`~Expanding.cov`, Sample covariance (binary) + :meth:`~Expanding.corr`, Sample correlation (binary) .. note:: @@ -884,6 +886,8 @@ Method summary windows. See :ref:`this section <computation.window_variance.caveats>` for more information. + The same caveats apply to using any supported statistical sample methods. + .. currentmodule:: pandas Aside from not having a ``window`` parameter, these functions have the same diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index e8fdaf0ae5d49..34f27c31febef 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -175,8 +175,8 @@ Other API changes - Added :meth:`DataFrame.value_counts` (:issue:`5377`) - :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`) - ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`) -- Using a :func:`pandas.api.indexers.BaseIndexer` with ``skew``, ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`) -- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`) +- Using a :func:`pandas.api.indexers.BaseIndexer` with ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`) +- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`) - Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations. - diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index 8707893dc20cf..082c2f533f3de 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -337,6 +337,7 @@ def validate_baseindexer_support(func_name: Optional[str]) -> None: "median", "std", "var", + "skew", "kurt", "quantile", } diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 3b14921528890..cdd61edba57ce 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -471,13 +471,13 @@ def _apply( def calc(x): x = np.concatenate((x, additional_nans)) - if not isinstance(window, BaseIndexer): + if not isinstance(self.window, BaseIndexer): min_periods = calculate_min_periods( window, self.min_periods, len(x), require_min_periods, floor ) else: min_periods = calculate_min_periods( - self.min_periods or 1, + window_indexer.window_size, self.min_periods, len(x), require_min_periods, diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py index aee47a085eb9c..15e6a904dd11a 100644 --- a/pandas/tests/window/test_base_indexer.py +++ b/pandas/tests/window/test_base_indexer.py @@ -82,7 +82,7 @@ def get_window_bounds(self, num_values, min_periods, center, closed): df.rolling(indexer, win_type="boxcar") -@pytest.mark.parametrize("func", ["skew", "cov", "corr"]) +@pytest.mark.parametrize("func", ["cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer): @@ -184,3 +184,29 @@ def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs) result3 = getattr(rolling3, func)() expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result3, expected3) + + +@pytest.mark.parametrize("constructor", [Series, DataFrame]) +def test_rolling_forward_skewness(constructor): + values = np.arange(10) + values[5] = 100.0 + + indexer = FixedForwardWindowIndexer(window_size=5) + rolling = constructor(values).rolling(window=indexer, min_periods=3) + result = rolling.skew() + + expected = constructor( + [ + 0.0, + 2.232396, + 2.229508, + 2.228340, + 2.229091, + 2.231989, + 0.0, + 0.0, + np.nan, + np.nan, + ] + ) + tm.assert_equal(result, expected)
- [X] xref #32865 - [X] 1 tests added / 1 passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry ## Scope of PR This PR does a couple things to fix the performance of `skew`, and this also fixes the behavior of all the functions that have `require_min_periods` for small values of `min_periods`: * clarify docs. Name all sample methods uniformly, add a note to the caveat that users should in general be careful about using sample methods with windows * fix bug in `_apply` that made us never go into the `BaseIndexer` control flow branch * fix bug in `_apply`: pass `window_indexer.window_size` into `calc_min_periods` instead of `min_periods or 1`. We want the custom indexer window size there, so it's not clear to me why we were passing `min_periods or 1` . ## Details The algorithm itself is robust, but it defaults to sample skewness, which is why there was a difference between its output and `numpy`. To prevent misunderstandings, I clarified the docs a bit. We were also passing a wrong value to `calc_min_periods`, and we weren't going into the proper if branch, because we were checking the type of `window` instead of `self.window`. ## Background on the wider issue We currently don't support several rolling window functions when building a rolling window object using a custom class descended from `pandas.api.indexers.Baseindexer`. The implementations were written with backward-looking windows in mind, and this led to these functions breaking. Currently, using these functions returns a `NotImplemented` error thanks to #33057, but ideally we want to update the implementations, so that they will work without a performance hit. This is what I aim to do over a series of PRs. ## Perf notes No changes to algorithms.
https://api.github.com/repos/pandas-dev/pandas/pulls/33745
2020-04-23T09:53:20Z
2020-04-25T22:03:14Z
2020-04-25T22:03:14Z
2020-04-26T06:01:34Z
TST: fix tests for asserting matching freq
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index fd23e95106ab0..c0e1eeb8f4eec 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -393,6 +393,9 @@ def test_numpy_repeat(self): @pytest.mark.parametrize("klass", [list, tuple, np.array, Series]) def test_where(self, klass): i = self.create_index() + if isinstance(i, (pd.DatetimeIndex, pd.TimedeltaIndex)): + # where does not preserve freq + i._set_freq(None) cond = [True] * len(i) result = i.where(klass(cond)) diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index 85d670e9dbffa..944358b1540b0 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -81,8 +81,8 @@ def test_map_dictlike(self, mapper): expected = index + index.freq # don't compare the freqs - if isinstance(expected, pd.DatetimeIndex): - expected._data.freq = None + if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)): + expected._set_freq(None) result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 34169a670c169..a299f03c5ebad 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -88,6 +88,7 @@ def test_astype_with_tz(self): result = idx.astype("datetime64[ns, US/Eastern]") expected = date_range("20170101 03:00:00", periods=4, tz="US/Eastern") tm.assert_index_equal(result, expected) + assert result.freq == expected.freq # GH 18951: tz-naive to tz-aware idx = date_range("20170101", periods=4) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 0247947ff19c5..a8e08bbe9a2e9 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -131,6 +131,7 @@ def test_construction_with_alt(self, kwargs, tz_aware_fixture): def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture): tz = tz_aware_fixture i = pd.date_range("20130101", periods=5, freq="H", tz=tz) + i._set_freq(None) kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()} if "tz" in kwargs: @@ -703,7 +704,9 @@ def test_constructor_start_end_with_tz(self, tz): end = Timestamp("2013-01-02 06:00:00", tz="America/Los_Angeles") result = date_range(freq="D", start=start, end=end, tz=tz) expected = DatetimeIndex( - ["2013-01-01 06:00:00", "2013-01-02 06:00:00"], tz="America/Los_Angeles" + ["2013-01-01 06:00:00", "2013-01-02 06:00:00"], + tz="America/Los_Angeles", + freq="D", ) tm.assert_index_equal(result, expected) # Especially assert that the timezone is consistent for pytz diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index b8200bb686aad..6ddbe4a5ce0a5 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -218,7 +218,7 @@ def test_date_range_normalize(self): rng = date_range(snap, periods=n, normalize=False, freq="2D") offset = timedelta(2) - values = DatetimeIndex([snap + i * offset for i in range(n)]) + values = DatetimeIndex([snap + i * offset for i in range(n)], freq=offset) tm.assert_index_equal(rng, values) @@ -413,7 +413,7 @@ def test_construct_over_dst(self): pre_dst, pst_dst, ] - expected = DatetimeIndex(expect_data) + expected = DatetimeIndex(expect_data, freq="H") result = date_range(start="2010-11-7", periods=3, freq="H", tz="US/Pacific") tm.assert_index_equal(result, expected) @@ -427,7 +427,8 @@ def test_construct_with_different_start_end_string_format(self): Timestamp("2013-01-01 00:00:00+09:00"), Timestamp("2013-01-01 01:00:00+09:00"), Timestamp("2013-01-01 02:00:00+09:00"), - ] + ], + freq="H", ) tm.assert_index_equal(result, expected) @@ -442,7 +443,7 @@ def test_range_bug(self): result = date_range("2011-1-1", "2012-1-31", freq=offset) start = datetime(2011, 1, 1) - expected = DatetimeIndex([start + i * offset for i in range(5)]) + expected = DatetimeIndex([start + i * offset for i in range(5)], freq=offset) tm.assert_index_equal(result, expected) def test_range_tz_pytz(self): @@ -861,6 +862,7 @@ def test_bdays_and_open_boundaries(self, closed): bday_end = "2018-07-27" # Friday expected = pd.date_range(bday_start, bday_end, freq="D") tm.assert_index_equal(result, expected) + # Note: we do _not_ expect the freqs to match here def test_bday_near_overflow(self): # GH#24252 avoid doing unnecessary addition that _would_ overflow @@ -910,15 +912,19 @@ def test_daterange_bug_456(self): def test_cdaterange(self): result = bdate_range("2013-05-01", periods=3, freq="C") - expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-03"]) + expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-03"], freq="C") tm.assert_index_equal(result, expected) + assert result.freq == expected.freq def test_cdaterange_weekmask(self): result = bdate_range( "2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu" ) - expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-05"]) + expected = DatetimeIndex( + ["2013-05-01", "2013-05-02", "2013-05-05"], freq=result.freq + ) tm.assert_index_equal(result, expected) + assert result.freq == expected.freq # raise with non-custom freq msg = ( @@ -930,8 +936,11 @@ def test_cdaterange_weekmask(self): def test_cdaterange_holidays(self): result = bdate_range("2013-05-01", periods=3, freq="C", holidays=["2013-05-01"]) - expected = DatetimeIndex(["2013-05-02", "2013-05-03", "2013-05-06"]) + expected = DatetimeIndex( + ["2013-05-02", "2013-05-03", "2013-05-06"], freq=result.freq + ) tm.assert_index_equal(result, expected) + assert result.freq == expected.freq # raise with non-custom freq msg = ( @@ -949,8 +958,11 @@ def test_cdaterange_weekmask_and_holidays(self): weekmask="Sun Mon Tue Wed Thu", holidays=["2013-05-01"], ) - expected = DatetimeIndex(["2013-05-02", "2013-05-05", "2013-05-06"]) + expected = DatetimeIndex( + ["2013-05-02", "2013-05-05", "2013-05-06"], freq=result.freq + ) tm.assert_index_equal(result, expected) + assert result.freq == expected.freq # raise with non-custom freq msg = ( diff --git a/pandas/tests/indexes/period/test_astype.py b/pandas/tests/indexes/period/test_astype.py index b286191623ebb..fa1617bdfaa52 100644 --- a/pandas/tests/indexes/period/test_astype.py +++ b/pandas/tests/indexes/period/test_astype.py @@ -143,18 +143,24 @@ def test_astype_array_fallback(self): def test_period_astype_to_timestamp(self): pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") - exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"]) - tm.assert_index_equal(pi.astype("datetime64[ns]"), exp) + exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="MS") + res = pi.astype("datetime64[ns]") + tm.assert_index_equal(res, exp) + assert res.freq == exp.freq exp = DatetimeIndex(["2011-01-31", "2011-02-28", "2011-03-31"]) exp = exp + Timedelta(1, "D") - Timedelta(1, "ns") - tm.assert_index_equal(pi.astype("datetime64[ns]", how="end"), exp) + res = pi.astype("datetime64[ns]", how="end") + tm.assert_index_equal(res, exp) + assert res.freq == exp.freq exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern") res = pi.astype("datetime64[ns, US/Eastern]") - tm.assert_index_equal(pi.astype("datetime64[ns, US/Eastern]"), exp) + tm.assert_index_equal(res, exp) + assert res.freq == exp.freq exp = DatetimeIndex(["2011-01-31", "2011-02-28", "2011-03-31"], tz="US/Eastern") exp = exp + Timedelta(1, "D") - Timedelta(1, "ns") res = pi.astype("datetime64[ns, US/Eastern]", how="end") tm.assert_index_equal(res, exp) + assert res.freq == exp.freq diff --git a/pandas/tests/indexes/period/test_to_timestamp.py b/pandas/tests/indexes/period/test_to_timestamp.py index a7846d1864d40..c2328872aee1b 100644 --- a/pandas/tests/indexes/period/test_to_timestamp.py +++ b/pandas/tests/indexes/period/test_to_timestamp.py @@ -60,8 +60,9 @@ def test_to_timestamp_quarterly_bug(self): pindex = PeriodIndex(year=years, quarter=quarters) stamps = pindex.to_timestamp("D", "end") - expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex], freq="Q") + expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex]) tm.assert_index_equal(stamps, expected) + assert stamps.freq == expected.freq def test_to_timestamp_pi_mult(self): idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="2M", name="idx")
xref #33711, #33712
https://api.github.com/repos/pandas-dev/pandas/pulls/33737
2020-04-23T02:59:52Z
2020-04-23T18:55:56Z
2020-04-23T18:55:56Z
2020-04-23T18:56:34Z
REF: use _wrap_joined_index in PeriodIndex.join
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 3a721d8c8c320..cf653a6875a9c 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -2,7 +2,7 @@ Base and utility classes for tseries type pandas objects. """ from datetime import datetime -from typing import Any, List, Optional, Union +from typing import Any, List, Optional, Union, cast import numpy as np @@ -583,6 +583,22 @@ def delete(self, loc): arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) return type(self)._simple_new(arr, name=self.name) + # -------------------------------------------------------------------- + # Join/Set Methods + + def _wrap_joined_index(self, joined: np.ndarray, other): + assert other.dtype == self.dtype, (other.dtype, self.dtype) + name = get_op_result_name(self, other) + + if is_period_dtype(self.dtype): + freq = self.freq + else: + self = cast(DatetimeTimedeltaMixin, self) + freq = self.freq if self._can_fast_union(other) else None + new_data = type(self._data)._simple_new(joined, dtype=self.dtype, freq=freq) + + return type(self)._simple_new(new_data, name=name) + class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): """ @@ -878,15 +894,6 @@ def _is_convertible_to_index_for_join(cls, other: Index) -> bool: return True return False - def _wrap_joined_index(self, joined: np.ndarray, other): - assert other.dtype == self.dtype, (other.dtype, self.dtype) - name = get_op_result_name(self, other) - - freq = self.freq if self._can_fast_union(other) else None - new_data = type(self._data)._simple_new(joined, dtype=self.dtype, freq=freq) - - return type(self)._simple_new(new_data, name=name) - # -------------------------------------------------------------------- # List-Like Methods diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 56cb9e29761a6..957c01c2dca96 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -628,6 +628,7 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False) other, how=how, level=level, return_indexers=return_indexers, sort=sort ) + # _assert_can_do_setop ensures we have matching dtype result = Int64Index.join( self, other, @@ -636,11 +637,7 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False) return_indexers=return_indexers, sort=sort, ) - - if return_indexers: - result, lidx, ridx = result - return self._apply_meta(result), lidx, ridx - return self._apply_meta(result) + return result # ------------------------------------------------------------------------ # Set Operation Methods @@ -719,13 +716,6 @@ def _union(self, other, sort): # ------------------------------------------------------------------------ - def _apply_meta(self, rawarr) -> "PeriodIndex": - if not isinstance(rawarr, PeriodIndex): - if not isinstance(rawarr, PeriodArray): - rawarr = PeriodArray(rawarr, freq=self.freq) - rawarr = PeriodIndex._simple_new(rawarr, name=self.name) - return rawarr - def memory_usage(self, deep=False): result = super().memory_usage(deep=deep) if hasattr(self, "_cache") and "_int64index" in self._cache:
PeriodIndex defines _apply_meta, but that is made unnecessary by implementing _wrap_joined_index correctly.
https://api.github.com/repos/pandas-dev/pandas/pulls/33736
2020-04-23T02:51:33Z
2020-04-23T17:13:46Z
2020-04-23T17:13:46Z
2020-04-23T17:54:22Z
REF: implement test_astype
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py new file mode 100644 index 0000000000000..dc779562b662d --- /dev/null +++ b/pandas/tests/frame/methods/test_astype.py @@ -0,0 +1,562 @@ +import re + +import numpy as np +import pytest + +from pandas import ( + Categorical, + CategoricalDtype, + DataFrame, + DatetimeTZDtype, + IntervalDtype, + NaT, + Series, + Timedelta, + Timestamp, + UInt64Index, + _np_version_under1p14, + concat, + date_range, + option_context, +) +import pandas._testing as tm +from pandas.core.arrays import integer_array + + +def _check_cast(df, v): + """ + Check if all dtypes of df are equal to v + """ + assert all(s.dtype.name == v for _, s in df.items()) + + +class TestAstype: + def test_astype_float(self, float_frame): + casted = float_frame.astype(int) + expected = DataFrame( + float_frame.values.astype(int), + index=float_frame.index, + columns=float_frame.columns, + ) + tm.assert_frame_equal(casted, expected) + + casted = float_frame.astype(np.int32) + expected = DataFrame( + float_frame.values.astype(np.int32), + index=float_frame.index, + columns=float_frame.columns, + ) + tm.assert_frame_equal(casted, expected) + + float_frame["foo"] = "5" + casted = float_frame.astype(int) + expected = DataFrame( + float_frame.values.astype(int), + index=float_frame.index, + columns=float_frame.columns, + ) + tm.assert_frame_equal(casted, expected) + + def test_astype_mixed_float(self, mixed_float_frame): + # mixed casting + casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32") + _check_cast(casted, "float32") + + casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16") + _check_cast(casted, "float16") + + def test_astype_mixed_type(self, mixed_type_frame): + # mixed casting + mn = mixed_type_frame._get_numeric_data().copy() + mn["little_float"] = np.array(12345.0, dtype="float16") + mn["big_float"] = np.array(123456789101112.0, dtype="float64") + + casted = mn.astype("float64") + _check_cast(casted, "float64") + + casted = mn.astype("int64") + _check_cast(casted, "int64") + + casted = mn.reindex(columns=["little_float"]).astype("float16") + _check_cast(casted, "float16") + + casted = mn.astype("float32") + _check_cast(casted, "float32") + + casted = mn.astype("int32") + _check_cast(casted, "int32") + + # to object + casted = mn.astype("O") + _check_cast(casted, "object") + + def test_astype_with_exclude_string(self, float_frame): + df = float_frame.copy() + expected = float_frame.astype(int) + df["string"] = "foo" + casted = df.astype(int, errors="ignore") + + expected["string"] = "foo" + tm.assert_frame_equal(casted, expected) + + df = float_frame.copy() + expected = float_frame.astype(np.int32) + df["string"] = "foo" + casted = df.astype(np.int32, errors="ignore") + + expected["string"] = "foo" + tm.assert_frame_equal(casted, expected) + + def test_astype_with_view_float(self, float_frame): + + # this is the only real reason to do it this way + tf = np.round(float_frame).astype(np.int32) + casted = tf.astype(np.float32, copy=False) + + # TODO(wesm): verification? + tf = float_frame.astype(np.float64) + casted = tf.astype(np.int64, copy=False) # noqa + + def test_astype_with_view_mixed_float(self, mixed_float_frame): + + tf = mixed_float_frame.reindex(columns=["A", "B", "C"]) + + casted = tf.astype(np.int64) + casted = tf.astype(np.float32) # noqa + + @pytest.mark.parametrize("dtype", [np.int32, np.int64]) + @pytest.mark.parametrize("val", [np.nan, np.inf]) + def test_astype_cast_nan_inf_int(self, val, dtype): + # see GH#14265 + # + # Check NaN and inf --> raise error when converting to int. + msg = "Cannot convert non-finite values \\(NA or inf\\) to integer" + df = DataFrame([val]) + + with pytest.raises(ValueError, match=msg): + df.astype(dtype) + + def test_astype_str(self): + # see GH#9757 + a = Series(date_range("2010-01-04", periods=5)) + b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern")) + c = Series([Timedelta(x, unit="d") for x in range(5)]) + d = Series(range(5)) + e = Series([0.0, 0.2, 0.4, 0.6, 0.8]) + + df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e}) + + # Datetime-like + result = df.astype(str) + + expected = DataFrame( + { + "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))), + "b": list(map(str, map(Timestamp, b._values))), + "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)), + "d": list(map(str, d._values)), + "e": list(map(str, e._values)), + } + ) + + tm.assert_frame_equal(result, expected) + + def test_astype_str_float(self): + # see GH#11302 + result = DataFrame([np.NaN]).astype(str) + expected = DataFrame(["nan"]) + + tm.assert_frame_equal(result, expected) + result = DataFrame([1.12345678901234567890]).astype(str) + + # < 1.14 truncates + # >= 1.14 preserves the full repr + val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457" + expected = DataFrame([val]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype_class", [dict, Series]) + def test_astype_dict_like(self, dtype_class): + # GH7271 & GH16717 + a = Series(date_range("2010-01-04", periods=5)) + b = Series(range(5)) + c = Series([0.0, 0.2, 0.4, 0.6, 0.8]) + d = Series(["1.0", "2", "3.14", "4", "5.4"]) + df = DataFrame({"a": a, "b": b, "c": c, "d": d}) + original = df.copy(deep=True) + + # change type of a subset of columns + dt1 = dtype_class({"b": "str", "d": "float32"}) + result = df.astype(dt1) + expected = DataFrame( + { + "a": a, + "b": Series(["0", "1", "2", "3", "4"]), + "c": c, + "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"), + } + ) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, original) + + dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64}) + result = df.astype(dt2) + expected = DataFrame( + { + "a": a, + "b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"), + "c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"), + "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"), + } + ) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, original) + + # change all columns + dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str}) + tm.assert_frame_equal(df.astype(dt3), df.astype(str)) + tm.assert_frame_equal(df, original) + + # error should be raised when using something other than column labels + # in the keys of the dtype dict + dt4 = dtype_class({"b": str, 2: str}) + dt5 = dtype_class({"e": str}) + msg = "Only a column name can be used for the key in a dtype mappings argument" + with pytest.raises(KeyError, match=msg): + df.astype(dt4) + with pytest.raises(KeyError, match=msg): + df.astype(dt5) + tm.assert_frame_equal(df, original) + + # if the dtypes provided are the same as the original dtypes, the + # resulting DataFrame should be the same as the original DataFrame + dt6 = dtype_class({col: df[col].dtype for col in df.columns}) + equiv = df.astype(dt6) + tm.assert_frame_equal(df, equiv) + tm.assert_frame_equal(df, original) + + # GH#16717 + # if dtypes provided is empty, the resulting DataFrame + # should be the same as the original DataFrame + dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object) + equiv = df.astype(dt7) + tm.assert_frame_equal(df, equiv) + tm.assert_frame_equal(df, original) + + def test_astype_duplicate_col(self): + a1 = Series([1, 2, 3, 4, 5], name="a") + b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b") + a2 = Series([0, 1, 2, 3, 4], name="a") + df = concat([a1, b, a2], axis=1) + + result = df.astype(str) + a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a") + b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype=str, name="b") + a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a") + expected = concat([a1_str, b_str, a2_str], axis=1) + tm.assert_frame_equal(result, expected) + + result = df.astype({"a": "str"}) + expected = concat([a1_str, b, a2_str], axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + [ + "category", + CategoricalDtype(), + CategoricalDtype(ordered=True), + CategoricalDtype(ordered=False), + CategoricalDtype(categories=list("abcdef")), + CategoricalDtype(categories=list("edba"), ordered=False), + CategoricalDtype(categories=list("edcb"), ordered=True), + ], + ids=repr, + ) + def test_astype_categorical(self, dtype): + # GH#18099 + d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")} + df = DataFrame(d) + result = df.astype(dtype) + expected = DataFrame({k: Categorical(d[k], dtype=dtype) for k in d}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype]) + def test_astype_categoricaldtype_class_raises(self, cls): + df = DataFrame({"A": ["a", "a", "b", "c"]}) + xpr = f"Expected an instance of {cls.__name__}" + with pytest.raises(TypeError, match=xpr): + df.astype({"A": cls}) + + with pytest.raises(TypeError, match=xpr): + df["A"].astype(cls) + + @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"]) + def test_astype_extension_dtypes(self, dtype): + # GH#22578 + df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"]) + + expected1 = DataFrame( + { + "a": integer_array([1, 3, 5], dtype=dtype), + "b": integer_array([2, 4, 6], dtype=dtype), + } + ) + tm.assert_frame_equal(df.astype(dtype), expected1) + tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) + tm.assert_frame_equal(df.astype(dtype).astype("float64"), df) + + df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"]) + df["b"] = df["b"].astype(dtype) + expected2 = DataFrame( + {"a": [1.0, 3.0, 5.0], "b": integer_array([2, 4, 6], dtype=dtype)} + ) + tm.assert_frame_equal(df, expected2) + + tm.assert_frame_equal(df.astype(dtype), expected1) + tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) + + @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"]) + def test_astype_extension_dtypes_1d(self, dtype): + # GH#22578 + df = DataFrame({"a": [1.0, 2.0, 3.0]}) + + expected1 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) + tm.assert_frame_equal(df.astype(dtype), expected1) + tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) + + df = DataFrame({"a": [1.0, 2.0, 3.0]}) + df["a"] = df["a"].astype(dtype) + expected2 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) + tm.assert_frame_equal(df, expected2) + + tm.assert_frame_equal(df.astype(dtype), expected1) + tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) + + @pytest.mark.parametrize("dtype", ["category", "Int64"]) + def test_astype_extension_dtypes_duplicate_col(self, dtype): + # GH#24704 + a1 = Series([0, np.nan, 4], name="a") + a2 = Series([np.nan, 3, 5], name="a") + df = concat([a1, a2], axis=1) + + result = df.astype(dtype) + expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"] + ) + def test_astype_column_metadata(self, dtype): + # GH#19920 + columns = UInt64Index([100, 200, 300], name="foo") + df = DataFrame(np.arange(15).reshape(5, 3), columns=columns) + df = df.astype(dtype) + tm.assert_index_equal(df.columns, columns) + + @pytest.mark.parametrize("dtype", ["M8", "m8"]) + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) + def test_astype_from_datetimelike_to_object(self, dtype, unit): + # tests astype to object dtype + # GH#19223 / GH#12425 + dtype = f"{dtype}[{unit}]" + arr = np.array([[1, 2, 3]], dtype=dtype) + df = DataFrame(arr) + result = df.astype(object) + assert (result.dtypes == object).all() + + if dtype.startswith("M8"): + assert result.iloc[0, 0] == Timestamp(1, unit=unit) + else: + assert result.iloc[0, 0] == Timedelta(1, unit=unit) + + @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"]) + def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit): + # tests all units from numeric origination + # GH#19223 / GH#12425 + dtype = f"{dtype}[{unit}]" + arr = np.array([[1, 2, 3]], dtype=arr_dtype) + df = DataFrame(arr) + result = df.astype(dtype) + expected = DataFrame(arr.astype(dtype)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) + def test_astype_to_datetime_unit(self, unit): + # tests all units from datetime origination + # GH#19223 + dtype = f"M8[{unit}]" + arr = np.array([[1, 2, 3]], dtype=dtype) + df = DataFrame(arr) + result = df.astype(dtype) + expected = DataFrame(arr.astype(dtype)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("unit", ["ns"]) + def test_astype_to_timedelta_unit_ns(self, unit): + # preserver the timedelta conversion + # GH#19223 + dtype = f"m8[{unit}]" + arr = np.array([[1, 2, 3]], dtype=dtype) + df = DataFrame(arr) + result = df.astype(dtype) + expected = DataFrame(arr.astype(dtype)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"]) + def test_astype_to_timedelta_unit(self, unit): + # coerce to float + # GH#19223 + dtype = f"m8[{unit}]" + arr = np.array([[1, 2, 3]], dtype=dtype) + df = DataFrame(arr) + result = df.astype(dtype) + expected = DataFrame(df.values.astype(dtype).astype(float)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) + def test_astype_to_incorrect_datetimelike(self, unit): + # trying to astype a m to a M, or vice-versa + # GH#19224 + dtype = f"M8[{unit}]" + other = f"m8[{unit}]" + + df = DataFrame(np.array([[1, 2, 3]], dtype=dtype)) + msg = ( + fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to " + fr"\[timedelta64\[{unit}\]\]" + ) + with pytest.raises(TypeError, match=msg): + df.astype(other) + + msg = ( + fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to " + fr"\[datetime64\[{unit}\]\]" + ) + df = DataFrame(np.array([[1, 2, 3]], dtype=other)) + with pytest.raises(TypeError, match=msg): + df.astype(dtype) + + def test_astype_arg_for_errors(self): + # GH#14878 + + df = DataFrame([1, 2, 3]) + + msg = ( + "Expected value of kwarg 'errors' to be one of " + "['raise', 'ignore']. Supplied value is 'True'" + ) + with pytest.raises(ValueError, match=re.escape(msg)): + df.astype(np.float64, errors=True) + + df.astype(np.int8, errors="ignore") + + def test_astype_arg_for_errors_dictlist(self): + # GH#25905 + df = DataFrame( + [ + {"a": "1", "b": "16.5%", "c": "test"}, + {"a": "2.2", "b": "15.3", "c": "another_test"}, + ] + ) + expected = DataFrame( + [ + {"a": 1.0, "b": "16.5%", "c": "test"}, + {"a": 2.2, "b": "15.3", "c": "another_test"}, + ] + ) + type_dict = {"a": "float64", "b": "float64", "c": "object"} + + result = df.astype(dtype=type_dict, errors="ignore") + + tm.assert_frame_equal(result, expected) + + def test_astype_dt64tz(self, timezone_frame): + # astype + expected = np.array( + [ + [ + Timestamp("2013-01-01 00:00:00"), + Timestamp("2013-01-02 00:00:00"), + Timestamp("2013-01-03 00:00:00"), + ], + [ + Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), + NaT, + Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), + ], + [ + Timestamp("2013-01-01 00:00:00+0100", tz="CET"), + NaT, + Timestamp("2013-01-03 00:00:00+0100", tz="CET"), + ], + ], + dtype=object, + ).T + expected = DataFrame( + expected, + index=timezone_frame.index, + columns=timezone_frame.columns, + dtype=object, + ) + result = timezone_frame.astype(object) + tm.assert_frame_equal(result, expected) + + result = timezone_frame.astype("datetime64[ns]") + expected = DataFrame( + { + "A": date_range("20130101", periods=3), + "B": ( + date_range("20130101", periods=3, tz="US/Eastern") + .tz_convert("UTC") + .tz_localize(None) + ), + "C": ( + date_range("20130101", periods=3, tz="CET") + .tz_convert("UTC") + .tz_localize(None) + ), + } + ) + expected.iloc[1, 1] = NaT + expected.iloc[1, 2] = NaT + tm.assert_frame_equal(result, expected) + + def test_astype_dt64tz_to_str(self, timezone_frame): + # str formatting + result = timezone_frame.astype(str) + expected = DataFrame( + [ + [ + "2013-01-01", + "2013-01-01 00:00:00-05:00", + "2013-01-01 00:00:00+01:00", + ], + ["2013-01-02", "NaT", "NaT"], + [ + "2013-01-03", + "2013-01-03 00:00:00-05:00", + "2013-01-03 00:00:00+01:00", + ], + ], + columns=timezone_frame.columns, + ) + tm.assert_frame_equal(result, expected) + + with option_context("display.max_columns", 20): + result = str(timezone_frame) + assert ( + "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00" + ) in result + assert ( + "1 2013-01-02 NaT NaT" + ) in result + assert ( + "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00" + ) in result diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 27ebee4aaaccf..9d0c221923cda 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -1,26 +1,14 @@ from collections import OrderedDict from datetime import timedelta -import re import numpy as np import pytest -from pandas.core.dtypes.dtypes import CategoricalDtype, DatetimeTZDtype, IntervalDtype +from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd -from pandas import ( - Categorical, - DataFrame, - Series, - Timedelta, - Timestamp, - _np_version_under1p14, - concat, - date_range, - option_context, -) +from pandas import DataFrame, Series, Timestamp, date_range, option_context import pandas._testing as tm -from pandas.core.arrays import integer_array def _check_cast(df, v): @@ -126,266 +114,6 @@ def test_dtypes_gh8722(self, float_string_frame): result = df.dtypes tm.assert_series_equal(result, Series({0: np.dtype("int64")})) - def test_astype_float(self, float_frame): - casted = float_frame.astype(int) - expected = DataFrame( - float_frame.values.astype(int), - index=float_frame.index, - columns=float_frame.columns, - ) - tm.assert_frame_equal(casted, expected) - - casted = float_frame.astype(np.int32) - expected = DataFrame( - float_frame.values.astype(np.int32), - index=float_frame.index, - columns=float_frame.columns, - ) - tm.assert_frame_equal(casted, expected) - - float_frame["foo"] = "5" - casted = float_frame.astype(int) - expected = DataFrame( - float_frame.values.astype(int), - index=float_frame.index, - columns=float_frame.columns, - ) - tm.assert_frame_equal(casted, expected) - - def test_astype_mixed_float(self, mixed_float_frame): - # mixed casting - casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32") - _check_cast(casted, "float32") - - casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16") - _check_cast(casted, "float16") - - def test_astype_mixed_type(self, mixed_type_frame): - # mixed casting - mn = mixed_type_frame._get_numeric_data().copy() - mn["little_float"] = np.array(12345.0, dtype="float16") - mn["big_float"] = np.array(123456789101112.0, dtype="float64") - - casted = mn.astype("float64") - _check_cast(casted, "float64") - - casted = mn.astype("int64") - _check_cast(casted, "int64") - - casted = mn.reindex(columns=["little_float"]).astype("float16") - _check_cast(casted, "float16") - - casted = mn.astype("float32") - _check_cast(casted, "float32") - - casted = mn.astype("int32") - _check_cast(casted, "int32") - - # to object - casted = mn.astype("O") - _check_cast(casted, "object") - - def test_astype_with_exclude_string(self, float_frame): - df = float_frame.copy() - expected = float_frame.astype(int) - df["string"] = "foo" - casted = df.astype(int, errors="ignore") - - expected["string"] = "foo" - tm.assert_frame_equal(casted, expected) - - df = float_frame.copy() - expected = float_frame.astype(np.int32) - df["string"] = "foo" - casted = df.astype(np.int32, errors="ignore") - - expected["string"] = "foo" - tm.assert_frame_equal(casted, expected) - - def test_astype_with_view_float(self, float_frame): - - # this is the only real reason to do it this way - tf = np.round(float_frame).astype(np.int32) - casted = tf.astype(np.float32, copy=False) - - # TODO(wesm): verification? - tf = float_frame.astype(np.float64) - casted = tf.astype(np.int64, copy=False) # noqa - - def test_astype_with_view_mixed_float(self, mixed_float_frame): - - tf = mixed_float_frame.reindex(columns=["A", "B", "C"]) - - casted = tf.astype(np.int64) - casted = tf.astype(np.float32) # noqa - - @pytest.mark.parametrize("dtype", [np.int32, np.int64]) - @pytest.mark.parametrize("val", [np.nan, np.inf]) - def test_astype_cast_nan_inf_int(self, val, dtype): - # see gh-14265 - # - # Check NaN and inf --> raise error when converting to int. - msg = "Cannot convert non-finite values \\(NA or inf\\) to integer" - df = DataFrame([val]) - - with pytest.raises(ValueError, match=msg): - df.astype(dtype) - - def test_astype_str(self): - # see gh-9757 - a = Series(date_range("2010-01-04", periods=5)) - b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern")) - c = Series([Timedelta(x, unit="d") for x in range(5)]) - d = Series(range(5)) - e = Series([0.0, 0.2, 0.4, 0.6, 0.8]) - - df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e}) - - # Datetime-like - result = df.astype(str) - - expected = DataFrame( - { - "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))), - "b": list(map(str, map(Timestamp, b._values))), - "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)), - "d": list(map(str, d._values)), - "e": list(map(str, e._values)), - } - ) - - tm.assert_frame_equal(result, expected) - - def test_astype_str_float(self): - # see gh-11302 - result = DataFrame([np.NaN]).astype(str) - expected = DataFrame(["nan"]) - - tm.assert_frame_equal(result, expected) - result = DataFrame([1.12345678901234567890]).astype(str) - - # < 1.14 truncates - # >= 1.14 preserves the full repr - val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457" - expected = DataFrame([val]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("dtype_class", [dict, Series]) - def test_astype_dict_like(self, dtype_class): - # GH7271 & GH16717 - a = Series(date_range("2010-01-04", periods=5)) - b = Series(range(5)) - c = Series([0.0, 0.2, 0.4, 0.6, 0.8]) - d = Series(["1.0", "2", "3.14", "4", "5.4"]) - df = DataFrame({"a": a, "b": b, "c": c, "d": d}) - original = df.copy(deep=True) - - # change type of a subset of columns - dt1 = dtype_class({"b": "str", "d": "float32"}) - result = df.astype(dt1) - expected = DataFrame( - { - "a": a, - "b": Series(["0", "1", "2", "3", "4"]), - "c": c, - "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"), - } - ) - tm.assert_frame_equal(result, expected) - tm.assert_frame_equal(df, original) - - dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64}) - result = df.astype(dt2) - expected = DataFrame( - { - "a": a, - "b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"), - "c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"), - "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"), - } - ) - tm.assert_frame_equal(result, expected) - tm.assert_frame_equal(df, original) - - # change all columns - dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str}) - tm.assert_frame_equal(df.astype(dt3), df.astype(str)) - tm.assert_frame_equal(df, original) - - # error should be raised when using something other than column labels - # in the keys of the dtype dict - dt4 = dtype_class({"b": str, 2: str}) - dt5 = dtype_class({"e": str}) - msg = "Only a column name can be used for the key in a dtype mappings argument" - with pytest.raises(KeyError, match=msg): - df.astype(dt4) - with pytest.raises(KeyError, match=msg): - df.astype(dt5) - tm.assert_frame_equal(df, original) - - # if the dtypes provided are the same as the original dtypes, the - # resulting DataFrame should be the same as the original DataFrame - dt6 = dtype_class({col: df[col].dtype for col in df.columns}) - equiv = df.astype(dt6) - tm.assert_frame_equal(df, equiv) - tm.assert_frame_equal(df, original) - - # GH 16717 - # if dtypes provided is empty, the resulting DataFrame - # should be the same as the original DataFrame - dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object) - equiv = df.astype(dt7) - tm.assert_frame_equal(df, equiv) - tm.assert_frame_equal(df, original) - - def test_astype_duplicate_col(self): - a1 = Series([1, 2, 3, 4, 5], name="a") - b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b") - a2 = Series([0, 1, 2, 3, 4], name="a") - df = concat([a1, b, a2], axis=1) - - result = df.astype(str) - a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a") - b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype=str, name="b") - a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a") - expected = concat([a1_str, b_str, a2_str], axis=1) - tm.assert_frame_equal(result, expected) - - result = df.astype({"a": "str"}) - expected = concat([a1_str, b, a2_str], axis=1) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "dtype", - [ - "category", - CategoricalDtype(), - CategoricalDtype(ordered=True), - CategoricalDtype(ordered=False), - CategoricalDtype(categories=list("abcdef")), - CategoricalDtype(categories=list("edba"), ordered=False), - CategoricalDtype(categories=list("edcb"), ordered=True), - ], - ids=repr, - ) - def test_astype_categorical(self, dtype): - # GH 18099 - d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")} - df = DataFrame(d) - result = df.astype(dtype) - expected = DataFrame({k: Categorical(d[k], dtype=dtype) for k in d}) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype]) - def test_astype_categoricaldtype_class_raises(self, cls): - df = DataFrame({"A": ["a", "a", "b", "c"]}) - xpr = f"Expected an instance of {cls.__name__}" - with pytest.raises(TypeError, match=xpr): - df.astype({"A": cls}) - - with pytest.raises(TypeError, match=xpr): - df["A"].astype(cls) - def test_singlerow_slice_categoricaldtype_gives_series(self): # GH29521 df = pd.DataFrame({"x": pd.Categorical("a b c d e".split())}) @@ -395,158 +123,6 @@ def test_singlerow_slice_categoricaldtype_gives_series(self): tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"]) - def test_astype_extension_dtypes(self, dtype): - # GH 22578 - df = pd.DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"]) - - expected1 = pd.DataFrame( - { - "a": integer_array([1, 3, 5], dtype=dtype), - "b": integer_array([2, 4, 6], dtype=dtype), - } - ) - tm.assert_frame_equal(df.astype(dtype), expected1) - tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) - tm.assert_frame_equal(df.astype(dtype).astype("float64"), df) - - df = pd.DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"]) - df["b"] = df["b"].astype(dtype) - expected2 = pd.DataFrame( - {"a": [1.0, 3.0, 5.0], "b": integer_array([2, 4, 6], dtype=dtype)} - ) - tm.assert_frame_equal(df, expected2) - - tm.assert_frame_equal(df.astype(dtype), expected1) - tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) - - @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"]) - def test_astype_extension_dtypes_1d(self, dtype): - # GH 22578 - df = pd.DataFrame({"a": [1.0, 2.0, 3.0]}) - - expected1 = pd.DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) - tm.assert_frame_equal(df.astype(dtype), expected1) - tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) - - df = pd.DataFrame({"a": [1.0, 2.0, 3.0]}) - df["a"] = df["a"].astype(dtype) - expected2 = pd.DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) - tm.assert_frame_equal(df, expected2) - - tm.assert_frame_equal(df.astype(dtype), expected1) - tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) - - @pytest.mark.parametrize("dtype", ["category", "Int64"]) - def test_astype_extension_dtypes_duplicate_col(self, dtype): - # GH 24704 - a1 = Series([0, np.nan, 4], name="a") - a2 = Series([np.nan, 3, 5], name="a") - df = concat([a1, a2], axis=1) - - result = df.astype(dtype) - expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"] - ) - def test_astype_column_metadata(self, dtype): - # GH 19920 - columns = pd.UInt64Index([100, 200, 300], name="foo") - df = DataFrame(np.arange(15).reshape(5, 3), columns=columns) - df = df.astype(dtype) - tm.assert_index_equal(df.columns, columns) - - @pytest.mark.parametrize("dtype", ["M8", "m8"]) - @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) - def test_astype_from_datetimelike_to_object(self, dtype, unit): - # tests astype to object dtype - # gh-19223 / gh-12425 - dtype = f"{dtype}[{unit}]" - arr = np.array([[1, 2, 3]], dtype=dtype) - df = DataFrame(arr) - result = df.astype(object) - assert (result.dtypes == object).all() - - if dtype.startswith("M8"): - assert result.iloc[0, 0] == pd.to_datetime(1, unit=unit) - else: - assert result.iloc[0, 0] == pd.to_timedelta(1, unit=unit) - - @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"]) - def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit): - # tests all units from numeric origination - # gh-19223 / gh-12425 - dtype = f"{dtype}[{unit}]" - arr = np.array([[1, 2, 3]], dtype=arr_dtype) - df = DataFrame(arr) - result = df.astype(dtype) - expected = DataFrame(arr.astype(dtype)) - - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) - def test_astype_to_datetime_unit(self, unit): - # tests all units from datetime origination - # gh-19223 - dtype = f"M8[{unit}]" - arr = np.array([[1, 2, 3]], dtype=dtype) - df = DataFrame(arr) - result = df.astype(dtype) - expected = DataFrame(arr.astype(dtype)) - - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("unit", ["ns"]) - def test_astype_to_timedelta_unit_ns(self, unit): - # preserver the timedelta conversion - # gh-19223 - dtype = f"m8[{unit}]" - arr = np.array([[1, 2, 3]], dtype=dtype) - df = DataFrame(arr) - result = df.astype(dtype) - expected = DataFrame(arr.astype(dtype)) - - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"]) - def test_astype_to_timedelta_unit(self, unit): - # coerce to float - # gh-19223 - dtype = f"m8[{unit}]" - arr = np.array([[1, 2, 3]], dtype=dtype) - df = DataFrame(arr) - result = df.astype(dtype) - expected = DataFrame(df.values.astype(dtype).astype(float)) - - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) - def test_astype_to_incorrect_datetimelike(self, unit): - # trying to astype a m to a M, or vice-versa - # gh-19224 - dtype = f"M8[{unit}]" - other = f"m8[{unit}]" - - df = DataFrame(np.array([[1, 2, 3]], dtype=dtype)) - msg = ( - fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to " - fr"\[timedelta64\[{unit}\]\]" - ) - with pytest.raises(TypeError, match=msg): - df.astype(other) - - msg = ( - fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to " - fr"\[datetime64\[{unit}\]\]" - ) - df = DataFrame(np.array([[1, 2, 3]], dtype=other)) - with pytest.raises(TypeError, match=msg): - df.astype(dtype) - def test_timedeltas(self): df = DataFrame( dict( @@ -586,40 +162,6 @@ def test_timedeltas(self): ) tm.assert_series_equal(result, expected) - def test_arg_for_errors_in_astype(self): - # issue #14878 - - df = DataFrame([1, 2, 3]) - - msg = ( - "Expected value of kwarg 'errors' to be one of " - "['raise', 'ignore']. Supplied value is 'True'" - ) - with pytest.raises(ValueError, match=re.escape(msg)): - df.astype(np.float64, errors=True) - - df.astype(np.int8, errors="ignore") - - def test_arg_for_errors_in_astype_dictlist(self): - # GH-25905 - df = pd.DataFrame( - [ - {"a": "1", "b": "16.5%", "c": "test"}, - {"a": "2.2", "b": "15.3", "c": "another_test"}, - ] - ) - expected = pd.DataFrame( - [ - {"a": 1.0, "b": "16.5%", "c": "test"}, - {"a": 2.2, "b": "15.3", "c": "another_test"}, - ] - ) - type_dict = {"a": "float64", "b": "float64", "c": "object"} - - result = df.astype(dtype=type_dict, errors="ignore") - - tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize( "input_vals", [ @@ -785,87 +327,3 @@ def test_interleave(self, timezone_frame): dtype=object, ).T tm.assert_numpy_array_equal(result, expected) - - def test_astype(self, timezone_frame): - # astype - expected = np.array( - [ - [ - Timestamp("2013-01-01 00:00:00"), - Timestamp("2013-01-02 00:00:00"), - Timestamp("2013-01-03 00:00:00"), - ], - [ - Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"), - pd.NaT, - Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"), - ], - [ - Timestamp("2013-01-01 00:00:00+0100", tz="CET"), - pd.NaT, - Timestamp("2013-01-03 00:00:00+0100", tz="CET"), - ], - ], - dtype=object, - ).T - expected = DataFrame( - expected, - index=timezone_frame.index, - columns=timezone_frame.columns, - dtype=object, - ) - result = timezone_frame.astype(object) - tm.assert_frame_equal(result, expected) - - result = timezone_frame.astype("datetime64[ns]") - expected = DataFrame( - { - "A": date_range("20130101", periods=3), - "B": ( - date_range("20130101", periods=3, tz="US/Eastern") - .tz_convert("UTC") - .tz_localize(None) - ), - "C": ( - date_range("20130101", periods=3, tz="CET") - .tz_convert("UTC") - .tz_localize(None) - ), - } - ) - expected.iloc[1, 1] = pd.NaT - expected.iloc[1, 2] = pd.NaT - tm.assert_frame_equal(result, expected) - - def test_astype_str(self, timezone_frame): - # str formatting - result = timezone_frame.astype(str) - expected = DataFrame( - [ - [ - "2013-01-01", - "2013-01-01 00:00:00-05:00", - "2013-01-01 00:00:00+01:00", - ], - ["2013-01-02", "NaT", "NaT"], - [ - "2013-01-03", - "2013-01-03 00:00:00-05:00", - "2013-01-03 00:00:00+01:00", - ], - ], - columns=timezone_frame.columns, - ) - tm.assert_frame_equal(result, expected) - - with option_context("display.max_columns", 20): - result = str(timezone_frame) - assert ( - "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00" - ) in result - assert ( - "1 2013-01-02 NaT NaT" - ) in result - assert ( - "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00" - ) in result diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py new file mode 100644 index 0000000000000..a4a0cb1978325 --- /dev/null +++ b/pandas/tests/indexes/categorical/test_astype.py @@ -0,0 +1,66 @@ +import numpy as np +import pytest + +from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index, IntervalIndex +import pandas._testing as tm + + +class TestAstype: + def test_astype(self): + ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + + result = ci.astype(object) + tm.assert_index_equal(result, Index(np.array(ci))) + + # this IS equal, but not the same class + assert result.equals(ci) + assert isinstance(result, Index) + assert not isinstance(result, CategoricalIndex) + + # interval + ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right") + + ci = CategoricalIndex( + Categorical.from_codes([0, 1, -1], categories=ii, ordered=True) + ) + + result = ci.astype("interval") + expected = ii.take([0, 1, -1]) + tm.assert_index_equal(result, expected) + + result = IntervalIndex(result.values) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("name", [None, "foo"]) + @pytest.mark.parametrize("dtype_ordered", [True, False]) + @pytest.mark.parametrize("index_ordered", [True, False]) + def test_astype_category(self, name, dtype_ordered, index_ordered): + # GH#18630 + index = CategoricalIndex( + list("aabbca"), categories=list("cab"), ordered=index_ordered + ) + if name: + index = index.rename(name) + + # standard categories + dtype = CategoricalDtype(ordered=dtype_ordered) + result = index.astype(dtype) + expected = CategoricalIndex( + index.tolist(), + name=name, + categories=index.categories, + ordered=dtype_ordered, + ) + tm.assert_index_equal(result, expected) + + # non-standard categories + dtype = CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered) + result = index.astype(dtype) + expected = CategoricalIndex(index.tolist(), name=name, dtype=dtype) + tm.assert_index_equal(result, expected) + + if dtype_ordered is False: + # dtype='category' can't specify ordered, so only test once + result = index.astype("category") + expected = index + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 83fe21fd20bfe..9765c77c6b60c 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -3,10 +3,8 @@ from pandas._libs import index as libindex -from pandas.core.dtypes.dtypes import CategoricalDtype - import pandas as pd -from pandas import Categorical, IntervalIndex +from pandas import Categorical import pandas._testing as tm from pandas.core.indexes.api import CategoricalIndex, Index @@ -196,63 +194,6 @@ def test_delete(self): # Either depending on NumPy version ci.delete(10) - def test_astype(self): - - ci = self.create_index() - result = ci.astype(object) - tm.assert_index_equal(result, Index(np.array(ci))) - - # this IS equal, but not the same class - assert result.equals(ci) - assert isinstance(result, Index) - assert not isinstance(result, CategoricalIndex) - - # interval - ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right") - - ci = CategoricalIndex( - Categorical.from_codes([0, 1, -1], categories=ii, ordered=True) - ) - - result = ci.astype("interval") - expected = ii.take([0, 1, -1]) - tm.assert_index_equal(result, expected) - - result = IntervalIndex(result.values) - tm.assert_index_equal(result, expected) - - @pytest.mark.parametrize("name", [None, "foo"]) - @pytest.mark.parametrize("dtype_ordered", [True, False]) - @pytest.mark.parametrize("index_ordered", [True, False]) - def test_astype_category(self, name, dtype_ordered, index_ordered): - # GH 18630 - index = self.create_index(ordered=index_ordered) - if name: - index = index.rename(name) - - # standard categories - dtype = CategoricalDtype(ordered=dtype_ordered) - result = index.astype(dtype) - expected = CategoricalIndex( - index.tolist(), - name=name, - categories=index.categories, - ordered=dtype_ordered, - ) - tm.assert_index_equal(result, expected) - - # non-standard categories - dtype = CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered) - result = index.astype(dtype) - expected = CategoricalIndex(index.tolist(), name=name, dtype=dtype) - tm.assert_index_equal(result, expected) - - if dtype_ordered is False: - # dtype='category' can't specify ordered, so only test once - result = index.astype("category") - expected = index - tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( "data, non_lexsorted_data", [[[1, 2, 3], [9, 0, 1, 2, 3]], [list("abc"), list("fabcd")]], diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 34169a670c169..7001dba442d16 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -12,7 +12,6 @@ Int64Index, NaT, PeriodIndex, - Series, Timestamp, date_range, ) @@ -65,37 +64,21 @@ def test_astype_with_tz(self): ) tm.assert_index_equal(result, expected) - # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex - result = pd.Series(pd.date_range("2012-01-01", periods=3)).astype(str) - expected = pd.Series(["2012-01-01", "2012-01-02", "2012-01-03"], dtype=object) - tm.assert_series_equal(result, expected) - - result = Series(pd.date_range("2012-01-01", periods=3, tz="US/Eastern")).astype( - str - ) - expected = Series( - [ - "2012-01-01 00:00:00-05:00", - "2012-01-02 00:00:00-05:00", - "2012-01-03 00:00:00-05:00", - ], - dtype=object, - ) - tm.assert_series_equal(result, expected) - + def test_astype_tzaware_to_tzaware(self): # GH 18951: tz-aware to tz-aware idx = date_range("20170101", periods=4, tz="US/Pacific") result = idx.astype("datetime64[ns, US/Eastern]") expected = date_range("20170101 03:00:00", periods=4, tz="US/Eastern") tm.assert_index_equal(result, expected) + def test_astype_tznaive_to_tzaware(self): # GH 18951: tz-naive to tz-aware idx = date_range("20170101", periods=4) result = idx.astype("datetime64[ns, US/Eastern]") expected = date_range("20170101", periods=4, tz="US/Eastern") tm.assert_index_equal(result, expected) - def test_astype_str_compat(self): + def test_astype_str_nat(self): # GH 13149, GH 13209 # verify that we are returning NaT as a string (and not unicode) @@ -106,7 +89,8 @@ def test_astype_str_compat(self): def test_astype_str(self): # test astype string - #10442 - result = date_range("2012-01-01", periods=4, name="test_name").astype(str) + dti = date_range("2012-01-01", periods=4, name="test_name") + result = dti.astype(str) expected = Index( ["2012-01-01", "2012-01-02", "2012-01-03", "2012-01-04"], name="test_name", @@ -114,10 +98,10 @@ def test_astype_str(self): ) tm.assert_index_equal(result, expected) + def test_astype_str_tz_and_name(self): # test astype string with tz and name - result = date_range( - "2012-01-01", periods=3, name="test_name", tz="US/Eastern" - ).astype(str) + dti = date_range("2012-01-01", periods=3, name="test_name", tz="US/Eastern") + result = dti.astype(str) expected = Index( [ "2012-01-01 00:00:00-05:00", @@ -129,10 +113,10 @@ def test_astype_str(self): ) tm.assert_index_equal(result, expected) + def test_astype_str_freq_and_name(self): # test astype string with freqH and name - result = date_range("1/1/2011", periods=3, freq="H", name="test_name").astype( - str - ) + dti = date_range("1/1/2011", periods=3, freq="H", name="test_name") + result = dti.astype(str) expected = Index( ["2011-01-01 00:00:00", "2011-01-01 01:00:00", "2011-01-01 02:00:00"], name="test_name", @@ -140,10 +124,12 @@ def test_astype_str(self): ) tm.assert_index_equal(result, expected) + def test_astype_str_freq_and_tz(self): # test astype string with freqH and timezone - result = date_range( + dti = date_range( "3/6/2012 00:00", periods=2, freq="H", tz="Europe/London", name="test_name" - ).astype(str) + ) + result = dti.astype(str) expected = Index( ["2012-03-06 00:00:00+00:00", "2012-03-06 01:00:00+00:00"], dtype=object, diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py new file mode 100644 index 0000000000000..1771f4336df67 --- /dev/null +++ b/pandas/tests/indexes/numeric/test_astype.py @@ -0,0 +1,83 @@ +import re + +import numpy as np +import pytest + +from pandas.core.dtypes.common import pandas_dtype + +from pandas import Float64Index, Index, Int64Index +import pandas._testing as tm + + +class TestAstype: + def test_astype_float64_to_object(self): + float_index = Float64Index([0.0, 2.5, 5.0, 7.5, 10.0]) + result = float_index.astype(object) + assert result.equals(float_index) + assert float_index.equals(result) + assert isinstance(result, Index) and not isinstance(result, Float64Index) + + def test_astype_float64_mixed_to_object(self): + # mixed int-float + idx = Float64Index([1.5, 2, 3, 4, 5]) + idx.name = "foo" + result = idx.astype(object) + assert result.equals(idx) + assert idx.equals(result) + assert isinstance(result, Index) and not isinstance(result, Float64Index) + + @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"]) + def test_astype_float64_to_int_dtype(self, dtype): + # GH#12881 + # a float astype int + idx = Float64Index([0, 1, 2]) + result = idx.astype(dtype) + expected = Int64Index([0, 1, 2]) + tm.assert_index_equal(result, expected) + + idx = Float64Index([0, 1.1, 2]) + result = idx.astype(dtype) + expected = Int64Index([0, 1, 2]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_astype_float64_to_float_dtype(self, dtype): + # GH#12881 + # a float astype int + idx = Float64Index([0, 1, 2]) + result = idx.astype(dtype) + expected = idx + tm.assert_index_equal(result, expected) + + idx = Float64Index([0, 1.1, 2]) + result = idx.astype(dtype) + expected = Index(idx.values.astype(dtype)) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) + def test_cannot_cast_to_datetimelike(self, dtype): + idx = Float64Index([0, 1.1, 2]) + + msg = ( + f"Cannot convert Float64Index to dtype {pandas_dtype(dtype)}; " + f"integer values are required for conversion" + ) + with pytest.raises(TypeError, match=re.escape(msg)): + idx.astype(dtype) + + @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"]) + @pytest.mark.parametrize("non_finite", [np.inf, np.nan]) + def test_cannot_cast_inf_to_int(self, non_finite, dtype): + # GH#13149 + idx = Float64Index([1, 2, non_finite]) + + msg = r"Cannot convert non-finite values \(NA or inf\) to integer" + with pytest.raises(ValueError, match=msg): + idx.astype(dtype) + + def test_astype_from_object(self): + index = Index([1.0, np.nan, 0.2], dtype="object") + result = index.astype(float) + expected = Float64Index([1.0, np.nan, 0.2]) + assert result.dtype == expected.dtype + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 35a1cbd141c89..0965694e5b51d 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -1,5 +1,4 @@ from datetime import datetime, timedelta -import re import numpy as np import pytest @@ -9,7 +8,6 @@ import pandas as pd from pandas import Float64Index, Index, Int64Index, Series, UInt64Index import pandas._testing as tm -from pandas.api.types import pandas_dtype from pandas.tests.indexes.common import Base @@ -213,67 +211,6 @@ def test_constructor_explicit(self, mixed_index, float_index): mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False ) - def test_astype(self, mixed_index, float_index): - - result = float_index.astype(object) - assert result.equals(float_index) - assert float_index.equals(result) - self.check_is_index(result) - - i = mixed_index.copy() - i.name = "foo" - result = i.astype(object) - assert result.equals(i) - assert i.equals(result) - self.check_is_index(result) - - # GH 12881 - # a float astype int - for dtype in ["int16", "int32", "int64"]: - i = Float64Index([0, 1, 2]) - result = i.astype(dtype) - expected = Int64Index([0, 1, 2]) - tm.assert_index_equal(result, expected) - - i = Float64Index([0, 1.1, 2]) - result = i.astype(dtype) - expected = Int64Index([0, 1, 2]) - tm.assert_index_equal(result, expected) - - for dtype in ["float32", "float64"]: - i = Float64Index([0, 1, 2]) - result = i.astype(dtype) - expected = i - tm.assert_index_equal(result, expected) - - i = Float64Index([0, 1.1, 2]) - result = i.astype(dtype) - expected = Index(i.values.astype(dtype)) - tm.assert_index_equal(result, expected) - - # invalid - for dtype in ["M8[ns]", "m8[ns]"]: - msg = ( - f"Cannot convert Float64Index to dtype {pandas_dtype(dtype)}; " - f"integer values are required for conversion" - ) - with pytest.raises(TypeError, match=re.escape(msg)): - i.astype(dtype) - - # GH 13149 - for dtype in ["int16", "int32", "int64"]: - i = Float64Index([0, 1.1, np.NAN]) - msg = r"Cannot convert non-finite values \(NA or inf\) to integer" - with pytest.raises(ValueError, match=msg): - i.astype(dtype) - - def test_cannot_cast_inf_to_int(self): - idx = pd.Float64Index([1, 2, np.inf]) - - msg = r"Cannot convert non-finite values \(NA or inf\) to integer" - with pytest.raises(ValueError, match=msg): - idx.astype(int) - def test_type_coercion_fail(self, any_int_dtype): # see gh-15832 msg = "Trying to coerce float values to integers" @@ -359,13 +296,6 @@ def test_nan_multiple_containment(self): i = Float64Index([1.0, 2.0]) tm.assert_numpy_array_equal(i.isin([np.nan]), np.array([False, False])) - def test_astype_from_object(self): - index = Index([1.0, np.nan, 0.2], dtype="object") - result = index.astype(float) - expected = Float64Index([1.0, np.nan, 0.2]) - assert result.dtype == expected.dtype - tm.assert_index_equal(result, expected) - def test_fillna_float64(self): # GH 11343 idx = Index([1.0, np.nan, 3.0], dtype=float, name="x") diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py new file mode 100644 index 0000000000000..9fdc4179de2e1 --- /dev/null +++ b/pandas/tests/series/methods/test_astype.py @@ -0,0 +1,25 @@ +from pandas import Series, date_range +import pandas._testing as tm + + +class TestAstype: + def test_astype_dt64_to_str(self): + # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex + dti = date_range("2012-01-01", periods=3) + result = Series(dti).astype(str) + expected = Series(["2012-01-01", "2012-01-02", "2012-01-03"], dtype=object) + tm.assert_series_equal(result, expected) + + def test_astype_dt64tz_to_str(self): + # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex + dti_tz = date_range("2012-01-01", periods=3, tz="US/Eastern") + result = Series(dti_tz).astype(str) + expected = Series( + [ + "2012-01-01 00:00:00-05:00", + "2012-01-02 00:00:00-05:00", + "2012-01-03 00:00:00-05:00", + ], + dtype=object, + ) + tm.assert_series_equal(result, expected)
Split/parametrized in some places.
https://api.github.com/repos/pandas-dev/pandas/pulls/33734
2020-04-23T00:50:13Z
2020-04-25T21:00:43Z
2020-04-25T21:00:43Z
2020-04-25T21:02:48Z
CLN: Remove unused assignment
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 04ebaf26fc11c..8228edb12b29a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8325,7 +8325,6 @@ def blk_func(values): result = result.iloc[0].rename(None) return result - data = self if numeric_only is None: data = self values = data.values
https://api.github.com/repos/pandas-dev/pandas/pulls/33733
2020-04-22T22:03:23Z
2020-04-23T01:00:43Z
2020-04-23T01:00:43Z
2020-04-23T02:51:20Z
BLD: bump numpy min version to 1.15.4
diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-36-minimum_versions.yaml index ae8fffa59fd50..f5af7bcf36189 100644 --- a/ci/deps/azure-36-minimum_versions.yaml +++ b/ci/deps/azure-36-minimum_versions.yaml @@ -1,6 +1,5 @@ name: pandas-dev channels: - - defaults - conda-forge dependencies: - python=3.6.1 @@ -19,12 +18,12 @@ dependencies: - jinja2=2.8 - numba=0.46.0 - numexpr=2.6.2 - - numpy=1.13.3 + - numpy=1.15.4 - openpyxl=2.5.7 - pytables=3.4.3 - python-dateutil=2.7.3 - pytz=2017.2 - - scipy=0.19.0 + - scipy=1.2 - xlrd=1.1.0 - xlsxwriter=0.9.8 - xlwt=1.2.0 diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml index 93885afbc4114..eeea249a19ca1 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-36.yaml @@ -19,7 +19,7 @@ dependencies: - matplotlib=2.2.3 - nomkl - numexpr - - numpy=1.14 + - numpy=1.15.4 - openpyxl - pyarrow>=0.13.0 - pytables diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index 47f63c11d0567..e833ea1f1f398 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -20,12 +20,12 @@ requirements: - cython - numpy - setuptools >=3.3 - - python-dateutil >=2.5.0 + - python-dateutil >=2.7.3 - pytz run: - python {{ python }} - {{ pin_compatible('numpy') }} - - python-dateutil >=2.5.0 + - python-dateutil >=2.7.3 - pytz test: diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index d392e151e3f97..ba99aaa9f430c 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -220,7 +220,7 @@ Dependencies Package Minimum supported version ================================================================ ========================== `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ 24.2.0 -`NumPy <https://www.numpy.org>`__ 1.13.3 +`NumPy <https://www.numpy.org>`__ 1.15.4 `python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.7.3 `pytz <https://pypi.org/project/pytz/>`__ 2017.2 ================================================================ ========================== diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 40adeb28d47b6..26aee8133a1e9 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -157,13 +157,23 @@ Other enhancements Increased minimum versions for dependencies ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Some minimum supported versions of dependencies were updated (:issue:`29766`, :issue:`29723`, pytables >= 3.4.3). +Some minimum supported versions of dependencies were updated (:issue:`33718`, :issue:`29766`, :issue:`29723`, pytables >= 3.4.3). If installed, we now require: +-----------------+-----------------+----------+---------+ | Package | Minimum Version | Required | Changed | +=================+=================+==========+=========+ -| python-dateutil | 2.7.3 | X | | +| numpy | 1.15.4 | X | X | ++-----------------+-----------------+----------+---------+ +| pytz | 2015.4 | X | | ++-----------------+-----------------+----------+---------+ +| python-dateutil | 2.7.3 | X | X | ++-----------------+-----------------+----------+---------+ +| bottleneck | 1.2.1 | | | ++-----------------+-----------------+----------+---------+ +| numexpr | 2.6.2 | | | ++-----------------+-----------------+----------+---------+ +| pytest (dev) | 4.0.2 | | | +-----------------+-----------------+----------+---------+ For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version. @@ -195,7 +205,7 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | s3fs | 0.3.0 | | +-----------------+-----------------+---------+ -| scipy | 0.19.0 | | +| scipy | 1.2.0 | X | +-----------------+-----------------+---------+ | sqlalchemy | 1.1.4 | | +-----------------+-----------------+---------+ diff --git a/environment.yml b/environment.yml index 8893302b4c9b2..bc7c715104ce5 100644 --- a/environment.yml +++ b/environment.yml @@ -75,7 +75,7 @@ dependencies: - jinja2 # pandas.Styler - matplotlib>=2.2.2 # pandas.plotting, Series.plot, DataFrame.plot - numexpr>=2.6.8 - - scipy>=1.1 + - scipy>=1.2 - numba>=0.46.0 # optional for io diff --git a/pandas/__init__.py b/pandas/__init__.py index 2b9a461e0e95d..d6584bf4f1c4f 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -20,8 +20,6 @@ # numpy compat from pandas.compat.numpy import ( - _np_version_under1p14, - _np_version_under1p15, _np_version_under1p16, _np_version_under1p17, _np_version_under1p18, diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 7e253a52a9c00..c5fd294699c45 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -21,7 +21,7 @@ "pytest": "5.0.1", "pyxlsb": "1.0.6", "s3fs": "0.3.0", - "scipy": "0.19.0", + "scipy": "1.2.0", "sqlalchemy": "1.1.4", "tables": "3.4.3", "tabulate": "0.8.3", diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index 6c9ac5944e6a1..a8f49d91f040e 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -8,19 +8,17 @@ # numpy versioning _np_version = np.__version__ _nlv = LooseVersion(_np_version) -_np_version_under1p14 = _nlv < LooseVersion("1.14") -_np_version_under1p15 = _nlv < LooseVersion("1.15") _np_version_under1p16 = _nlv < LooseVersion("1.16") _np_version_under1p17 = _nlv < LooseVersion("1.17") _np_version_under1p18 = _nlv < LooseVersion("1.18") _is_numpy_dev = ".dev" in str(_nlv) -if _nlv < "1.13.3": +if _nlv < "1.15.4": raise ImportError( - "this version of pandas is incompatible with numpy < 1.13.3\n" + "this version of pandas is incompatible with numpy < 1.15.4\n" f"your numpy version is {_np_version}.\n" - "Please upgrade numpy to >= 1.13.3 to use this pandas version" + "Please upgrade numpy to >= 1.15.4 to use this pandas version" ) @@ -65,8 +63,6 @@ def np_array_datetime64_compat(arr, *args, **kwargs): __all__ = [ "np", "_np_version", - "_np_version_under1p14", - "_np_version_under1p15", "_np_version_under1p16", "_np_version_under1p17", "_is_numpy_dev", diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index 5aab5b814bae7..ecd20796b6f21 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -193,8 +193,6 @@ class TestPDApi(Base): "_hashtable", "_lib", "_libs", - "_np_version_under1p14", - "_np_version_under1p15", "_np_version_under1p16", "_np_version_under1p17", "_np_version_under1p18", diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py index 69f8f46356a4d..74a11c9f33195 100644 --- a/pandas/tests/dtypes/cast/test_promote.py +++ b/pandas/tests/dtypes/cast/test_promote.py @@ -98,14 +98,13 @@ def _assert_match(result_fill_value, expected_fill_value): # GH#23982/25425 require the same type in addition to equality/NA-ness res_type = type(result_fill_value) ex_type = type(expected_fill_value) - if res_type.__name__ == "uint64": - # No idea why, but these (sometimes) do not compare as equal - assert ex_type.__name__ == "uint64" - elif res_type.__name__ == "ulonglong": - # On some builds we get this instead of np.uint64 - # Note: cant check res_type.dtype.itemsize directly on numpy 1.18 - assert res_type(0).itemsize == 8 - assert ex_type == res_type or ex_type == np.uint64 + + if hasattr(result_fill_value, "dtype"): + # Compare types in a way that is robust to platform-specific + # idiosyncracies where e.g. sometimes we get "ulonglong" as an alias + # for "uint64" or "intc" as an alias for "int32" + assert result_fill_value.dtype.kind == expected_fill_value.dtype.kind + assert result_fill_value.dtype.itemsize == expected_fill_value.dtype.itemsize else: # On some builds, type comparison fails, e.g. np.int32 != np.int32 assert res_type == ex_type or res_type.__name__ == ex_type.__name__ diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 50b72698629bb..04dedac3e8b9b 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -16,8 +16,6 @@ import numpy as np import pytest -from pandas.compat.numpy import _np_version_under1p14 - import pandas as pd import pandas._testing as tm from pandas.core.arrays.boolean import BooleanDtype @@ -111,9 +109,6 @@ def check_opname(self, s, op_name, other, exc=None): def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: if op_name in self.implements: - # subtraction for bools raises TypeError (but not yet in 1.13) - if _np_version_under1p14: - pytest.skip("__sub__ does not yet raise in numpy 1.13") msg = r"numpy boolean subtract" with pytest.raises(TypeError, match=msg): op(s, other) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index dc779562b662d..b06c3d72a2c77 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -14,7 +14,6 @@ Timedelta, Timestamp, UInt64Index, - _np_version_under1p14, concat, date_range, option_context, @@ -169,9 +168,7 @@ def test_astype_str_float(self): tm.assert_frame_equal(result, expected) result = DataFrame([1.12345678901234567890]).astype(str) - # < 1.14 truncates - # >= 1.14 preserves the full repr - val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457" + val = "1.1234567890123457" expected = DataFrame([val]) tm.assert_frame_equal(result, expected) diff --git a/pyproject.toml b/pyproject.toml index 696785599d7da..efeb24edbdeb1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,8 +5,8 @@ requires = [ "setuptools", "wheel", "Cython>=0.29.16", # Note: sync with setup.py - "numpy==1.13.3; python_version=='3.6' and platform_system!='AIX'", - "numpy==1.14.5; python_version>='3.7' and platform_system!='AIX'", + "numpy==1.15.4; python_version=='3.6' and platform_system!='AIX'", + "numpy==1.15.4; python_version>='3.7' and platform_system!='AIX'", "numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'", "numpy==1.16.0; python_version>='3.7' and platform_system=='AIX'", ] diff --git a/requirements-dev.txt b/requirements-dev.txt index 8a954fabd2d8d..5f5b5d27a03a7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -50,7 +50,7 @@ ipython>=7.11.1 jinja2 matplotlib>=2.2.2 numexpr>=2.6.8 -scipy>=1.1 +scipy>=1.2 numba>=0.46.0 beautifulsoup4>=4.6.0 html5lib diff --git a/setup.py b/setup.py index a2e01e08e8de2..58f3fb5706ad1 100755 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ def is_platform_mac(): return sys.platform == "darwin" -min_numpy_ver = "1.13.3" +min_numpy_ver = "1.15.4" min_cython_ver = "0.29.16" # note: sync with pyproject.toml try:
- [x] closes #33718 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33729
2020-04-22T20:31:06Z
2020-05-01T19:38:39Z
2020-05-01T19:38:38Z
2020-06-09T14:44:08Z
TST: pd.concat on two (or more) series produces all-NaN dataframe
diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index bccae2c4c2772..c4025640bb49f 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2768,3 +2768,37 @@ def test_concat_copy_index(test_series, axis): comb = concat([df, df], axis=axis, copy=True) assert comb.index is not df.index assert comb.columns is not df.columns + + +def test_concat_multiindex_datetime_object_index(): + # https://github.com/pandas-dev/pandas/issues/11058 + s = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2014, 1, 1)], dtype="object")], + names=["first", "second"], + ), + ) + s2 = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2015, 1, 1)], dtype="object")], + names=["first", "second"], + ), + ) + expected = DataFrame( + [["a", "a"], ["b", np.nan], [np.nan, "b"]], + index=MultiIndex.from_arrays( + [ + [1, 2, 2], + DatetimeIndex( + ["2013-01-01", "2014-01-01", "2015-01-01"], + dtype="datetime64[ns]", + freq=None, + ), + ], + names=["first", "second"], + ), + ) + result = concat([s, s2], axis=1) + tm.assert_frame_equal(result, expected)
- [ ] closes #11058 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33728
2020-04-22T19:25:46Z
2020-04-22T21:26:00Z
2020-04-22T21:26:00Z
2020-04-23T07:01:36Z
REF: avoid passing SingleBlockManager to Series
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6c3523f830e97..5defb8916c73f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3649,7 +3649,9 @@ def reindexer(value): @property def _series(self): return { - item: Series(self._mgr.iget(idx), index=self.index, name=item) + item: Series( + self._mgr.iget(idx), index=self.index, name=item, fastpath=True + ) for idx, item in enumerate(self.columns) } diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f35a5b6f9a7e..b2ed47465e395 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11208,9 +11208,7 @@ def block_accum_func(blk_values): result = self._mgr.apply(block_accum_func) - d = self._construct_axes_dict() - d["copy"] = False - return self._constructor(result, **d).__finalize__(self, method=name) + return self._constructor(result).__finalize__(self, method=name) return set_function_name(cum_func, name, cls) diff --git a/pandas/core/series.py b/pandas/core/series.py index 9ef865a964123..f990cc7ae7917 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -259,12 +259,8 @@ def __init__( # astype copies data = data.astype(dtype) else: - # need to copy to avoid aliasing issues + # GH#24096 we need to ensure the index remains immutable data = data._values.copy() - if isinstance(data, ABCDatetimeIndex) and data.tz is not None: - # GH#24096 need copy to be deep for datetime64tz case - # TODO: See if we can avoid these copies - data = data._values.copy(deep=True) copy = False elif isinstance(data, np.ndarray): @@ -281,6 +277,7 @@ def __init__( index = data.index else: data = data.reindex(index, copy=copy) + copy = False data = data._mgr elif is_dict_like(data): data, index = self._init_dict(data, index, dtype)
cc @jorisvandenbossche IIRC you didnt want to disallow SingleBlockManager because geopandas passes it. In those cases, does it also pass `fastpath=True`? If so, we can consider deprecating allowing SingleBlockManager in the non-fastpath case
https://api.github.com/repos/pandas-dev/pandas/pulls/33727
2020-04-22T18:14:00Z
2020-04-23T17:59:29Z
2020-04-23T17:59:29Z
2020-04-23T18:02:57Z
TYP: construction
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index cdd0717849e96..8a405d6ee0a00 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -330,7 +330,7 @@ def __init__( values = _convert_to_list_like(values) # By convention, empty lists result in object dtype: - sanitize_dtype = "object" if len(values) == 0 else None + sanitize_dtype = np.dtype("O") if len(values) == 0 else None null_mask = isna(values) if null_mask.any(): values = [values[idx] for idx in np.where(~null_mask)[0]] diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 2d60ad9ba50bf..d1b07585943ea 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -13,7 +13,7 @@ from pandas._libs import lib from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime -from pandas._typing import ArrayLike, Dtype +from pandas._typing import ArrayLike, Dtype, DtypeObj from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -36,7 +36,6 @@ is_list_like, is_object_dtype, is_timedelta64_ns_dtype, - pandas_dtype, ) from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, registry from pandas.core.dtypes.generic import ( @@ -52,13 +51,12 @@ if TYPE_CHECKING: from pandas.core.series import Series # noqa: F401 from pandas.core.indexes.api import Index # noqa: F401 + from pandas.core.arrays import ExtensionArray # noqa: F401 def array( - data: Sequence[object], - dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None, - copy: bool = True, -) -> ABCExtensionArray: + data: Sequence[object], dtype: Optional[Dtype] = None, copy: bool = True, +) -> "ExtensionArray": """ Create an array. @@ -388,14 +386,16 @@ def extract_array(obj, extract_numpy: bool = False): def sanitize_array( - data, index, dtype=None, copy: bool = False, raise_cast_failure: bool = False -): + data, + index: Optional["Index"], + dtype: Optional[DtypeObj] = None, + copy: bool = False, + raise_cast_failure: bool = False, +) -> ArrayLike: """ - Sanitize input data to an ndarray, copy if specified, coerce to the - dtype if specified. + Sanitize input data to an ndarray or ExtensionArray, copy if specified, + coerce to the dtype if specified. """ - if dtype is not None: - dtype = pandas_dtype(dtype) if isinstance(data, ma.MaskedArray): mask = ma.getmaskarray(data) @@ -508,10 +508,7 @@ def sanitize_array( def _try_cast( - arr, - dtype: Optional[Union[np.dtype, "ExtensionDtype"]], - copy: bool, - raise_cast_failure: bool, + arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bool, ): """ Convert input to numpy ndarray and optionally cast to a given dtype. diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index c9419fded5de9..e50d635a1ba6c 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -3,7 +3,7 @@ """ from datetime import date, datetime, timedelta -from typing import TYPE_CHECKING, Type +from typing import TYPE_CHECKING, Any, Optional, Tuple, Type import numpy as np @@ -17,7 +17,7 @@ iNaT, ) from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import Dtype, DtypeObj +from pandas._typing import ArrayLike, Dtype, DtypeObj from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.common import ( @@ -613,7 +613,7 @@ def _ensure_dtype_type(value, dtype): return dtype.type(value) -def infer_dtype_from(val, pandas_dtype: bool = False): +def infer_dtype_from(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]: """ Interpret the dtype from a scalar or array. @@ -630,7 +630,7 @@ def infer_dtype_from(val, pandas_dtype: bool = False): return infer_dtype_from_array(val, pandas_dtype=pandas_dtype) -def infer_dtype_from_scalar(val, pandas_dtype: bool = False): +def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]: """ Interpret the dtype from a scalar. @@ -641,7 +641,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): If False, scalar belongs to pandas extension types is inferred as object """ - dtype = np.object_ + dtype = np.dtype(object) # a 1-element ndarray if isinstance(val, np.ndarray): @@ -660,7 +660,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): # instead of np.empty (but then you still don't want things # coming out as np.str_! - dtype = np.object_ + dtype = np.dtype(object) elif isinstance(val, (np.datetime64, datetime)): val = tslibs.Timestamp(val) @@ -671,7 +671,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): dtype = DatetimeTZDtype(unit="ns", tz=val.tz) else: # return datetimetz as object - return np.object_, val + return np.dtype(object), val val = val.value elif isinstance(val, (np.timedelta64, timedelta)): @@ -679,22 +679,22 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): dtype = np.dtype("m8[ns]") elif is_bool(val): - dtype = np.bool_ + dtype = np.dtype(np.bool_) elif is_integer(val): if isinstance(val, np.integer): - dtype = type(val) + dtype = np.dtype(type(val)) else: - dtype = np.int64 + dtype = np.dtype(np.int64) elif is_float(val): if isinstance(val, np.floating): - dtype = type(val) + dtype = np.dtype(type(val)) else: - dtype = np.float64 + dtype = np.dtype(np.float64) elif is_complex(val): - dtype = np.complex_ + dtype = np.dtype(np.complex_) elif pandas_dtype: if lib.is_period(val): @@ -707,7 +707,8 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): return dtype, val -def infer_dtype_from_array(arr, pandas_dtype: bool = False): +# TODO: try to make the Any in the return annotation more specific +def infer_dtype_from_array(arr, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]: """ Infer the dtype from an array. @@ -738,7 +739,7 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False): array(['1', '1'], dtype='<U21') >>> infer_dtype_from_array([1, '1']) - (<class 'numpy.object_'>, [1, '1']) + (dtype('O'), [1, '1']) """ if isinstance(arr, np.ndarray): return arr.dtype, arr @@ -755,7 +756,7 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False): # don't force numpy coerce with nan's inferred = lib.infer_dtype(arr, skipna=False) if inferred in ["string", "bytes", "mixed", "mixed-integer"]: - return (np.object_, arr) + return (np.dtype(np.object_), arr) arr = np.asarray(arr) return arr.dtype, arr @@ -1469,7 +1470,7 @@ def find_common_type(types): return np.find_common_type(types, []) -def cast_scalar_to_array(shape, value, dtype=None): +def cast_scalar_to_array(shape, value, dtype: Optional[DtypeObj] = None) -> np.ndarray: """ Create np.ndarray of specified shape and dtype, filled with values. @@ -1496,7 +1497,9 @@ def cast_scalar_to_array(shape, value, dtype=None): return values -def construct_1d_arraylike_from_scalar(value, length: int, dtype): +def construct_1d_arraylike_from_scalar( + value, length: int, dtype: DtypeObj +) -> ArrayLike: """ create a np.ndarray / pandas type of specified shape and dtype filled with values @@ -1505,7 +1508,7 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype): ---------- value : scalar value length : int - dtype : pandas_dtype / np.dtype + dtype : pandas_dtype or np.dtype Returns ------- @@ -1517,8 +1520,6 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype): subarr = cls._from_sequence([value] * length, dtype=dtype) else: - if not isinstance(dtype, (np.dtype, type(np.dtype))): - dtype = dtype.dtype if length and is_integer_dtype(dtype) and isna(value): # coerce if we have nan for an integer dtype @@ -1536,7 +1537,7 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype): return subarr -def construct_1d_object_array_from_listlike(values): +def construct_1d_object_array_from_listlike(values) -> np.ndarray: """ Transform any list-like object in a 1-dimensional numpy array of object dtype. @@ -1561,7 +1562,9 @@ def construct_1d_object_array_from_listlike(values): return result -def construct_1d_ndarray_preserving_na(values, dtype=None, copy: bool = False): +def construct_1d_ndarray_preserving_na( + values, dtype: Optional[DtypeObj] = None, copy: bool = False +) -> np.ndarray: """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8228edb12b29a..6ff72691ca757 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -104,6 +104,7 @@ is_scalar, is_sequence, needs_i8_conversion, + pandas_dtype, ) from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -1917,7 +1918,12 @@ def to_records( @classmethod def _from_arrays( - cls, arrays, columns, index, dtype=None, verify_integrity=True + cls, + arrays, + columns, + index, + dtype: Optional[Dtype] = None, + verify_integrity: bool = True, ) -> "DataFrame": """ Create DataFrame from a list of arrays corresponding to the columns. @@ -1943,6 +1949,9 @@ def _from_arrays( ------- DataFrame """ + if dtype is not None: + dtype = pandas_dtype(dtype) + mgr = arrays_to_mgr( arrays, columns, diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 5c9e4b96047ee..ce3f07d06d6a2 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -3,13 +3,13 @@ constructors before passing them to a BlockManager. """ from collections import abc -from typing import Dict, List, Optional, Tuple, Union +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import numpy.ma as ma from pandas._libs import lib -from pandas._typing import Axis, Dtype, Scalar +from pandas._typing import Axis, DtypeObj, Scalar from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -50,12 +50,20 @@ create_block_manager_from_blocks, ) +if TYPE_CHECKING: + from pandas import Series # noqa:F401 + # --------------------------------------------------------------------- # BlockManager Interface def arrays_to_mgr( - arrays, arr_names, index, columns, dtype=None, verify_integrity: bool = True + arrays, + arr_names, + index, + columns, + dtype: Optional[DtypeObj] = None, + verify_integrity: bool = True, ): """ Segregate Series based on type and coerce into matrices. @@ -85,7 +93,9 @@ def arrays_to_mgr( return create_block_manager_from_arrays(arrays, arr_names, axes) -def masked_rec_array_to_mgr(data, index, columns, dtype, copy: bool): +def masked_rec_array_to_mgr( + data, index, columns, dtype: Optional[DtypeObj], copy: bool +): """ Extract from a masked rec array and create the manager. """ @@ -130,7 +140,7 @@ def masked_rec_array_to_mgr(data, index, columns, dtype, copy: bool): # DataFrame Constructor Interface -def init_ndarray(values, index, columns, dtype=None, copy=False): +def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): # input must be a ndarray, list, Series, index if isinstance(values, ABCSeries): @@ -189,7 +199,10 @@ def init_ndarray(values, index, columns, dtype=None, copy=False): f"failed to cast to '{dtype}' (Exception was: {orig})" ) from orig - index, columns = _get_axes(*values.shape, index=index, columns=columns) + # _prep_ndarray ensures that values.ndim == 2 at this point + index, columns = _get_axes( + values.shape[0], values.shape[1], index=index, columns=columns + ) values = values.T # if we don't have a dtype specified, then try to convert objects @@ -221,13 +234,15 @@ def init_ndarray(values, index, columns, dtype=None, copy=False): return create_block_manager_from_blocks(block_values, [columns, index]) -def init_dict(data, index, columns, dtype=None): +def init_dict(data: Dict, index, columns, dtype: Optional[DtypeObj] = None): """ Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. """ + arrays: Union[Sequence[Any], "Series"] + if columns is not None: - from pandas.core.series import Series + from pandas.core.series import Series # noqa:F811 arrays = Series(data, index=columns, dtype=object) data_names = arrays.index @@ -244,7 +259,7 @@ def init_dict(data, index, columns, dtype=None): if missing.any() and not is_integer_dtype(dtype): if dtype is None or np.issubdtype(dtype, np.flexible): # GH#1783 - nan_dtype = object + nan_dtype = np.dtype(object) else: nan_dtype = dtype val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype) @@ -253,7 +268,7 @@ def init_dict(data, index, columns, dtype=None): else: keys = list(data.keys()) columns = data_names = Index(keys) - arrays = (com.maybe_iterable_to_list(data[k]) for k in keys) + arrays = [com.maybe_iterable_to_list(data[k]) for k in keys] # GH#24096 need copy to be deep for datetime64tz case # TODO: See if we can avoid these copies arrays = [ @@ -308,7 +323,7 @@ def convert(v): return values -def _homogenize(data, index, dtype=None): +def _homogenize(data, index, dtype: Optional[DtypeObj]): oindex = None homogenized = [] @@ -339,7 +354,10 @@ def _homogenize(data, index, dtype=None): return homogenized -def extract_index(data): +def extract_index(data) -> Index: + """ + Try to infer an Index from the passed data, raise ValueError on failure. + """ index = None if len(data) == 0: index = Index([]) @@ -381,6 +399,7 @@ def extract_index(data): ) if have_series: + assert index is not None # for mypy if lengths[0] != len(index): msg = ( f"array length {lengths[0]} does not match index " @@ -442,7 +461,8 @@ def _get_axes(N, K, index, columns) -> Tuple[Index, Index]: def dataclasses_to_dicts(data): - """ Converts a list of dataclass instances to a list of dictionaries + """ + Converts a list of dataclass instances to a list of dictionaries. Parameters ---------- @@ -472,7 +492,9 @@ def dataclasses_to_dicts(data): # Conversion of Inputs to Arrays -def to_arrays(data, columns, coerce_float=False, dtype=None): +def to_arrays( + data, columns, coerce_float: bool = False, dtype: Optional[DtypeObj] = None +): """ Return list of arrays, columns. """ @@ -527,7 +549,7 @@ def _list_to_arrays( data: List[Scalar], columns: Union[Index, List], coerce_float: bool = False, - dtype: Optional[Dtype] = None, + dtype: Optional[DtypeObj] = None, ) -> Tuple[List[Scalar], Union[Index, List[Axis]]]: if len(data) > 0 and isinstance(data[0], tuple): content = list(lib.to_object_array_tuples(data).T) @@ -547,7 +569,7 @@ def _list_of_series_to_arrays( data: List, columns: Union[Index, List], coerce_float: bool = False, - dtype: Optional[Dtype] = None, + dtype: Optional[DtypeObj] = None, ) -> Tuple[List[Scalar], Union[Index, List[Axis]]]: if columns is None: # We know pass_data is non-empty because data[0] is a Series @@ -585,7 +607,7 @@ def _list_of_dict_to_arrays( data: List, columns: Union[Index, List], coerce_float: bool = False, - dtype: Optional[Dtype] = None, + dtype: Optional[DtypeObj] = None, ) -> Tuple[List[Scalar], Union[Index, List[Axis]]]: """ Convert list of dicts to numpy arrays @@ -624,7 +646,7 @@ def _list_of_dict_to_arrays( def _validate_or_indexify_columns( - content: List, columns: Union[Index, List, None] + content: List, columns: Optional[Union[Index, List]] ) -> Union[Index, List[Axis]]: """ If columns is None, make numbers as column names; Otherwise, validate that @@ -682,7 +704,7 @@ def _validate_or_indexify_columns( def _convert_object_array( - content: List[Scalar], coerce_float: bool = False, dtype: Optional[Dtype] = None + content: List[Scalar], coerce_float: bool = False, dtype: Optional[DtypeObj] = None ) -> List[Scalar]: """ Internal function ot convert object array. @@ -699,7 +721,7 @@ def _convert_object_array( """ # provide soft conversion of object dtypes def convert(arr): - if dtype != object and dtype != np.object: + if dtype != np.dtype("O"): arr = lib.maybe_convert_objects(arr, try_float=coerce_float) arr = maybe_cast_to_datetime(arr, dtype) return arr
https://api.github.com/repos/pandas-dev/pandas/pulls/33725
2020-04-22T14:47:13Z
2020-04-24T12:05:47Z
2020-04-24T12:05:47Z
2020-04-24T14:27:24Z
CLN: misc cleanups from LGTM.com
diff --git a/pandas/_testing.py b/pandas/_testing.py index 4f957b7a55e3a..21e74dafcc944 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -279,16 +279,10 @@ def write_to_compressed(compression, path, data, dest="test"): ValueError : An invalid compression value was passed in. """ if compression == "zip": - import zipfile - compress_method = zipfile.ZipFile elif compression == "gzip": - import gzip - compress_method = gzip.GzipFile elif compression == "bz2": - import bz2 - compress_method = bz2.BZ2File elif compression == "xz": compress_method = _get_lzma_file(lzma) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 202cb6488446e..d0276af2e9948 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8218,7 +8218,6 @@ def blk_func(values): result = result.iloc[0].rename(None) return result - data = self if numeric_only is None: data = self values = data.values diff --git a/pandas/core/series.py b/pandas/core/series.py index 9ef865a964123..a9db60f23f2e2 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -275,7 +275,6 @@ def __init__( "Cannot construct a Series from an ndarray with " "compound dtype. Use DataFrame instead." ) - pass elif isinstance(data, ABCSeries): if index is None: index = data.index
https://api.github.com/repos/pandas-dev/pandas/pulls/33724
2020-04-22T13:55:34Z
2020-04-23T03:09:11Z
2020-04-23T03:09:11Z
2020-04-23T07:03:00Z
BUG: Propagate Python exceptions from c_is_list_like (#33721)
diff --git a/pandas/_libs/lib.pxd b/pandas/_libs/lib.pxd index 12aca9dabe2e7..b3c72c30a74de 100644 --- a/pandas/_libs/lib.pxd +++ b/pandas/_libs/lib.pxd @@ -1 +1 @@ -cdef bint c_is_list_like(object, bint) +cdef bint c_is_list_like(object, bint) except -1 diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 5256bdc988995..14efab735fa7d 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -988,7 +988,7 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool: return c_is_list_like(obj, allow_sets) -cdef inline bint c_is_list_like(object obj, bint allow_sets): +cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1: return ( isinstance(obj, abc.Iterable) # we do not count strings/unicode/bytes as list-like diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 8b20f9ada8ff7..4c4a5547247fc 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -123,6 +123,17 @@ def test_is_list_like_disallow_sets(maybe_list_like): assert inference.is_list_like(obj, allow_sets=False) == expected +def test_is_list_like_recursion(): + # GH 33721 + # interpreter would crash with with SIGABRT + def foo(): + inference.is_list_like([]) + foo() + + with pytest.raises(RecursionError): + foo() + + def test_is_sequence(): is_seq = inference.is_sequence assert is_seq((1, 2))
- [x] closes #33721 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33723
2020-04-22T13:45:47Z
2020-04-27T18:58:07Z
2020-04-27T18:58:07Z
2020-04-27T18:58:11Z
TYP: add types to DataFrame._get_agg_axis
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6c3523f830e97..04ebaf26fc11c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8548,7 +8548,7 @@ def idxmax(self, axis=0, skipna=True) -> Series: result = [index[i] if i >= 0 else np.nan for i in indices] return Series(result, index=self._get_agg_axis(axis)) - def _get_agg_axis(self, axis_num): + def _get_agg_axis(self, axis_num: int) -> Index: """ Let's be explicit about this. """
Minor followup to #33610.
https://api.github.com/repos/pandas-dev/pandas/pulls/33722
2020-04-22T13:43:03Z
2020-04-22T18:31:51Z
2020-04-22T18:31:51Z
2020-04-22T18:31:58Z
BUG: DTA/TDA/PA setitem incorrectly allowing i8
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 9bc0dd7cc02e6..e902c4f7eb14f 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -773,7 +773,7 @@ def _validate_fill_value(self, fill_value): return fill_value def _validate_shift_value(self, fill_value): - # TODO(2.0): once this deprecation is enforced, used _validate_fill_value + # TODO(2.0): once this deprecation is enforced, use _validate_fill_value if is_valid_nat_for_dtype(fill_value, self.dtype): fill_value = NaT elif not isinstance(fill_value, self._recognized_scalars): @@ -813,6 +813,9 @@ def _validate_searchsorted_value(self, value): elif isinstance(value, self._recognized_scalars): value = self._scalar_type(value) + elif isinstance(value, type(self)): + pass + elif is_list_like(value) and not isinstance(value, type(self)): value = array(value) @@ -822,7 +825,7 @@ def _validate_searchsorted_value(self, value): f"not {type(value).__name__}" ) - if not (isinstance(value, (self._scalar_type, type(self))) or (value is NaT)): + else: raise TypeError(f"Unexpected type for 'value': {type(value)}") if isinstance(value, type(self)): @@ -834,18 +837,28 @@ def _validate_searchsorted_value(self, value): return value def _validate_setitem_value(self, value): - if lib.is_scalar(value) and not isna(value): - value = com.maybe_box_datetimelike(value) if is_list_like(value): - value = type(self)._from_sequence(value, dtype=self.dtype) - self._check_compatible_with(value, setitem=True) - value = value.asi8 - elif isinstance(value, self._scalar_type): - self._check_compatible_with(value, setitem=True) - value = self._unbox_scalar(value) + value = array(value) + if is_dtype_equal(value.dtype, "string"): + # We got a StringArray + try: + # TODO: Could use from_sequence_of_strings if implemented + # Note: passing dtype is necessary for PeriodArray tests + value = type(self)._from_sequence(value, dtype=self.dtype) + except ValueError: + pass + + if not type(self)._is_recognized_dtype(value): + raise TypeError( + "setitem requires compatible dtype or scalar, " + f"not {type(value).__name__}" + ) + + elif isinstance(value, self._recognized_scalars): + value = self._scalar_type(value) elif is_valid_nat_for_dtype(value, self.dtype): - value = iNaT + value = NaT else: msg = ( f"'value' should be a '{self._scalar_type.__name__}', 'NaT', " @@ -853,6 +866,12 @@ def _validate_setitem_value(self, value): ) raise TypeError(msg) + self._check_compatible_with(value, setitem=True) + if isinstance(value, type(self)): + value = value.asi8 + else: + value = self._unbox_scalar(value) + return value def _validate_insert_value(self, value): diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 5b703cfe8fae5..e84ebf3e479f1 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -241,6 +241,16 @@ def test_setitem(self): expected[:2] = expected[-2:] tm.assert_numpy_array_equal(arr.asi8, expected) + def test_setitem_str_array(self, arr1d): + if isinstance(arr1d, DatetimeArray) and arr1d.tz is not None: + pytest.xfail(reason="timezone comparisons inconsistent") + expected = arr1d.copy() + expected[[0, 1]] = arr1d[-2:] + + arr1d[:2] = [str(x) for x in arr1d[-2:]] + + tm.assert_equal(arr1d, expected) + def test_setitem_raises(self): data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9 arr = self.array_cls(data, freq="D") @@ -252,6 +262,17 @@ def test_setitem_raises(self): with pytest.raises(TypeError, match="'value' should be a.* 'object'"): arr[0] = object() + @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series]) + def test_setitem_numeric_raises(self, arr1d, box): + # We dont case e.g. int64 to our own dtype for setitem + + msg = "requires compatible dtype" + with pytest.raises(TypeError, match=msg): + arr1d[:2] = box([0, 1]) + + with pytest.raises(TypeError, match=msg): + arr1d[:2] = box([0.0, 1.0]) + def test_inplace_arithmetic(self): # GH#24115 check that iadd and isub are actually in-place data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33717
2020-04-21T23:26:39Z
2020-04-30T13:44:37Z
2020-04-30T13:44:37Z
2020-05-04T20:03:22Z
REF: implement _validate_comparison_value
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 27b2ed822a49f..63932e64d3b05 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -60,29 +60,24 @@ def _datetimelike_array_cmp(cls, op): opname = f"__{op.__name__}__" nat_result = opname == "__ne__" - @unpack_zerodim_and_defer(opname) - def wrapper(self, other): + class InvalidComparison(Exception): + pass + def _validate_comparison_value(self, other): if isinstance(other, str): try: # GH#18435 strings get a pass from tzawareness compat other = self._scalar_from_string(other) except ValueError: # failed to parse as Timestamp/Timedelta/Period - return invalid_comparison(self, other, op) + raise InvalidComparison(other) if isinstance(other, self._recognized_scalars) or other is NaT: other = self._scalar_type(other) self._check_compatible_with(other) - other_i8 = self._unbox_scalar(other) - - result = op(self.view("i8"), other_i8) - if isna(other): - result.fill(nat_result) - elif not is_list_like(other): - return invalid_comparison(self, other, op) + raise InvalidComparison(other) elif len(other) != len(self): raise ValueError("Lengths must match") @@ -93,34 +88,50 @@ def wrapper(self, other): other = np.array(other) if not isinstance(other, (np.ndarray, type(self))): - return invalid_comparison(self, other, op) - - if is_object_dtype(other): - # We have to use comp_method_OBJECT_ARRAY instead of numpy - # comparison otherwise it would fail to raise when - # comparing tz-aware and tz-naive - with np.errstate(all="ignore"): - result = ops.comp_method_OBJECT_ARRAY( - op, self.astype(object), other - ) - o_mask = isna(other) + raise InvalidComparison(other) + + elif is_object_dtype(other.dtype): + pass elif not type(self)._is_recognized_dtype(other.dtype): - return invalid_comparison(self, other, op) + raise InvalidComparison(other) else: # For PeriodDType this casting is unnecessary + # TODO: use Index to do inference? other = type(self)._from_sequence(other) self._check_compatible_with(other) - result = op(self.view("i8"), other.view("i8")) - o_mask = other._isnan + return other - if o_mask.any(): - result[o_mask] = nat_result + @unpack_zerodim_and_defer(opname) + def wrapper(self, other): - if self._hasnans: - result[self._isnan] = nat_result + try: + other = _validate_comparison_value(self, other) + except InvalidComparison: + return invalid_comparison(self, other, op) + + dtype = getattr(other, "dtype", None) + if is_object_dtype(dtype): + # We have to use comp_method_OBJECT_ARRAY instead of numpy + # comparison otherwise it would fail to raise when + # comparing tz-aware and tz-naive + with np.errstate(all="ignore"): + result = ops.comp_method_OBJECT_ARRAY(op, self.astype(object), other) + return result + + if isinstance(other, self._scalar_type) or other is NaT: + other_i8 = self._unbox_scalar(other) + else: + # Then type(other) == type(self) + other_i8 = other.asi8 + + result = op(self.asi8, other_i8) + + o_mask = isna(other) + if self._hasnans | np.any(o_mask): + result[self._isnan | o_mask] = nat_result return result
Trying to match the patterns we use for all the other DTA/TDA/PA methods that have an `other`-like arg. No logic should be changed here, just moved around.
https://api.github.com/repos/pandas-dev/pandas/pulls/33716
2020-04-21T23:15:51Z
2020-04-23T17:58:38Z
2020-04-23T17:58:38Z
2020-04-23T18:03:37Z
BUG: DTI/TDI/PI.where accepting incorrectly-typed NaTs
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index af5834f01c24c..3fd0a7f4467a8 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -869,27 +869,33 @@ def _validate_insert_value(self, value): def _validate_where_value(self, other): if is_valid_nat_for_dtype(other, self.dtype): - other = NaT.value + other = NaT + elif isinstance(other, self._recognized_scalars): + other = self._scalar_type(other) + self._check_compatible_with(other, setitem=True) elif not is_list_like(other): - # TODO: what about own-type scalars? raise TypeError(f"Where requires matching dtype, not {type(other)}") else: # Do type inference if necessary up front # e.g. we passed PeriodIndex.values and got an ndarray of Periods - from pandas import Index - - other = Index(other) + other = array(other) + other = extract_array(other, extract_numpy=True) - if is_categorical_dtype(other): + if is_categorical_dtype(other.dtype): # e.g. we have a Categorical holding self.dtype if is_dtype_equal(other.categories.dtype, self.dtype): other = other._internal_get_values() - if not is_dtype_equal(self.dtype, other.dtype): + if not type(self)._is_recognized_dtype(other.dtype): raise TypeError(f"Where requires matching dtype, not {other.dtype}") + self._check_compatible_with(other, setitem=True) + if lib.is_scalar(other): + other = self._unbox_scalar(other) + else: other = other.view("i8") + return other # ------------------------------------------------------------------ diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 2200eadf3874f..838bece11b050 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -530,7 +530,12 @@ def isin(self, values, level=None): def where(self, cond, other=None): values = self.view("i8") - other = self._data._validate_where_value(other) + try: + other = self._data._validate_where_value(other) + except (TypeError, ValueError) as err: + # Includes tzawareness mismatch and IncompatibleFrequencyError + oth = getattr(other, "dtype", other) + raise TypeError(f"Where requires matching dtype, not {oth}") from err result = np.where(cond, values, other).astype("i8") arr = type(self._data)._simple_new(result, dtype=self.dtype) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index f9b8bd27b7f5a..d813604400f9a 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -197,9 +197,15 @@ def test_where_invalid_dtypes(self): # non-matching scalar dti.where(notna(i2), pd.Timedelta(days=4)) - with pytest.raises(TypeError, match="Where requires matching dtype"): - # non-matching NA value - dti.where(notna(i2), np.timedelta64("NaT", "ns")) + def test_where_mismatched_nat(self, tz_aware_fixture): + tz = tz_aware_fixture + dti = pd.date_range("2013-01-01", periods=3, tz=tz) + cond = np.array([True, False, True]) + + msg = "Where requires matching dtype" + with pytest.raises(TypeError, match=msg): + # wrong-dtyped NaT + dti.where(cond, np.timedelta64("NaT", "ns")) def test_where_tz(self): i = pd.date_range("20130101", periods=3, tz="US/Eastern") diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index bd71c04a9ab03..f0efff4bbdd88 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -541,9 +541,14 @@ def test_where_invalid_dtypes(self): # non-matching scalar pi.where(notna(i2), Timedelta(days=4)) - with pytest.raises(TypeError, match="Where requires matching dtype"): - # non-matching NA value - pi.where(notna(i2), np.timedelta64("NaT", "ns")) + def test_where_mismatched_nat(self): + pi = period_range("20130101", periods=5, freq="D") + cond = np.array([True, False, True, True, False]) + + msg = "Where requires matching dtype" + with pytest.raises(TypeError, match=msg): + # wrong-dtyped NaT + pi.where(cond, np.timedelta64("NaT", "ns")) class TestTake: diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index 17feed3fd7a68..396a676b97a1b 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -163,9 +163,14 @@ def test_where_invalid_dtypes(self): # non-matching scalar tdi.where(notna(i2), pd.Timestamp.now()) - with pytest.raises(TypeError, match="Where requires matching dtype"): - # non-matching NA value - tdi.where(notna(i2), np.datetime64("NaT", "ns")) + def test_where_mismatched_nat(self): + tdi = timedelta_range("1 day", periods=3, freq="D", name="idx") + cond = np.array([True, False, False]) + + msg = "Where requires matching dtype" + with pytest.raises(TypeError, match=msg): + # wrong-dtyped NaT + tdi.where(cond, np.datetime64("NaT", "ns")) class TestTake: diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 6cb73823adabb..1e362827e823b 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -1,3 +1,4 @@ +from datetime import timedelta import itertools from typing import Dict, List @@ -686,8 +687,15 @@ def test_where_series_datetime64(self, fill_val, exp_dtype): ) self._assert_where_conversion(obj, cond, values, exp, exp_dtype) - def test_where_index_datetime(self): - fill_val = pd.Timestamp("2012-01-01") + @pytest.mark.parametrize( + "fill_val", + [ + pd.Timestamp("2012-01-01"), + pd.Timestamp("2012-01-01").to_datetime64(), + pd.Timestamp("2012-01-01").to_pydatetime(), + ], + ) + def test_where_index_datetime(self, fill_val): exp_dtype = "datetime64[ns]" obj = pd.Index( [ @@ -700,9 +708,9 @@ def test_where_index_datetime(self): assert obj.dtype == "datetime64[ns]" cond = pd.Index([True, False, True, False]) - msg = "Where requires matching dtype, not .*Timestamp" - with pytest.raises(TypeError, match=msg): - obj.where(cond, fill_val) + result = obj.where(cond, fill_val) + expected = pd.DatetimeIndex([obj[0], fill_val, obj[2], fill_val]) + tm.assert_index_equal(result, expected) values = pd.Index(pd.date_range(fill_val, periods=4)) exp = pd.Index( @@ -717,7 +725,7 @@ def test_where_index_datetime(self): self._assert_where_conversion(obj, cond, values, exp, exp_dtype) @pytest.mark.xfail(reason="GH 22839: do not ignore timezone, must be object") - def test_where_index_datetimetz(self): + def test_where_index_datetime64tz(self): fill_val = pd.Timestamp("2012-01-01", tz="US/Eastern") exp_dtype = np.object obj = pd.Index( @@ -754,23 +762,53 @@ def test_where_index_complex128(self): def test_where_index_bool(self): pass - def test_where_series_datetime64tz(self): - pass - def test_where_series_timedelta64(self): pass def test_where_series_period(self): pass - def test_where_index_datetime64tz(self): - pass + @pytest.mark.parametrize( + "value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")] + ) + def test_where_index_timedelta64(self, value): + tdi = pd.timedelta_range("1 Day", periods=4) + cond = np.array([True, False, False, True]) - def test_where_index_timedelta64(self): - pass + expected = pd.TimedeltaIndex(["1 Day", value, value, "4 Days"]) + result = tdi.where(cond, value) + tm.assert_index_equal(result, expected) + + msg = "Where requires matching dtype" + with pytest.raises(TypeError, match=msg): + # wrong-dtyped NaT + tdi.where(cond, np.datetime64("NaT", "ns")) def test_where_index_period(self): - pass + dti = pd.date_range("2016-01-01", periods=3, freq="QS") + pi = dti.to_period("Q") + + cond = np.array([False, True, False]) + + # Passinga valid scalar + value = pi[-1] + pi.freq * 10 + expected = pd.PeriodIndex([value, pi[1], value]) + result = pi.where(cond, value) + tm.assert_index_equal(result, expected) + + # Case passing ndarray[object] of Periods + other = np.asarray(pi + pi.freq * 10, dtype=object) + result = pi.where(cond, other) + expected = pd.PeriodIndex([other[0], pi[1], other[2]]) + tm.assert_index_equal(result, expected) + + # Passing a mismatched scalar + msg = "Where requires matching dtype" + with pytest.raises(TypeError, match=msg): + pi.where(cond, pd.Timedelta(days=4)) + + with pytest.raises(TypeError, match=msg): + pi.where(cond, pd.Period("2020-04-21", "D")) class TestFillnaSeriesCoercion(CoercionBase):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry In addition to the bug in the title, this makes DTI accept datetime/dt64, TDI accept timedelta/td64, and PI accept Period. This brings these into closer alignment with the other methods, which we ultimately want to make as consistent as possible.
https://api.github.com/repos/pandas-dev/pandas/pulls/33715
2020-04-21T23:08:10Z
2020-04-25T22:22:42Z
2020-04-25T22:22:42Z
2020-04-25T22:26:43Z
CLN: simplify DTA.__getitem__
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 27b2ed822a49f..5237bc6226169 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -527,21 +527,6 @@ def __getitem__(self, key): This getitem defers to the underlying array, which by-definition can only handle list-likes, slices, and integer scalars """ - is_int = lib.is_integer(key) - if lib.is_scalar(key) and not is_int: - raise IndexError( - "only integers, slices (`:`), ellipsis (`...`), " - "numpy.newaxis (`None`) and integer or boolean " - "arrays are valid indices" - ) - - getitem = self._data.__getitem__ - if is_int: - val = getitem(key) - if lib.is_scalar(val): - # i.e. self.ndim == 1 - return self._box_func(val) - return type(self)(val, dtype=self.dtype) if com.is_bool_indexer(key): # first convert to boolean, because check_array_indexer doesn't @@ -558,6 +543,16 @@ def __getitem__(self, key): else: key = check_array_indexer(self, key) + freq = self._get_getitem_freq(key) + result = self._data[key] + if lib.is_scalar(result): + return self._box_func(result) + return self._simple_new(result, dtype=self.dtype, freq=freq) + + def _get_getitem_freq(self, key): + """ + Find the `freq` attribute to assign to the result of a __getitem__ lookup. + """ is_period = is_period_dtype(self.dtype) if is_period: freq = self.freq @@ -572,11 +567,7 @@ def __getitem__(self, key): # GH#21282 indexing with Ellipsis is similar to a full slice, # should preserve `freq` attribute freq = self.freq - - result = getitem(key) - if lib.is_scalar(result): - return self._box_func(result) - return self._simple_new(result, dtype=self.dtype, freq=freq) + return freq def __setitem__( self,
https://api.github.com/repos/pandas-dev/pandas/pulls/33714
2020-04-21T22:48:35Z
2020-04-24T21:41:43Z
2020-04-24T21:41:43Z
2020-04-24T22:20:20Z
CLN: .values -> ._values
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 235b3113a2ae7..89e1c0fea2b32 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -299,7 +299,7 @@ def __init__( self.name = grouper.name if isinstance(grouper, MultiIndex): - self.grouper = grouper.values + self.grouper = grouper._values # we have a single grouper which may be a myriad of things, # some of which are dependent on the passing in level diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b67e3347e6af0..9275e4ba3ed25 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -112,22 +112,22 @@ def cmp_method(self, other): if other.ndim > 0 and len(self) != len(other): raise ValueError("Lengths must match to compare") - if is_object_dtype(self) and isinstance(other, ABCCategorical): + if is_object_dtype(self.dtype) and isinstance(other, ABCCategorical): left = type(other)(self._values, dtype=other.dtype) return op(left, other) - elif is_object_dtype(self) and isinstance(other, ExtensionArray): + elif is_object_dtype(self.dtype) and isinstance(other, ExtensionArray): # e.g. PeriodArray with np.errstate(all="ignore"): - result = op(self.values, other) + result = op(self._values, other) - elif is_object_dtype(self) and not isinstance(self, ABCMultiIndex): + elif is_object_dtype(self.dtype) and not isinstance(self, ABCMultiIndex): # don't pass MultiIndex with np.errstate(all="ignore"): - result = ops.comp_method_OBJECT_ARRAY(op, self.values, other) + result = ops.comp_method_OBJECT_ARRAY(op, self._values, other) else: with np.errstate(all="ignore"): - result = op(self.values, np.asarray(other)) + result = op(self._values, np.asarray(other)) if is_bool_dtype(result): return result @@ -510,7 +510,7 @@ def _shallow_copy(self, values=None, name: Label = no_default): name = self.name if name is no_default else name cache = self._cache.copy() if values is None else {} if values is None: - values = self.values + values = self._values result = self._simple_new(values, name=name) result._cache = cache @@ -722,7 +722,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): indices = ensure_platform_int(indices) if self._can_hold_na: taken = self._assert_take_fillable( - self.values, + self._values, indices, allow_fill=allow_fill, fill_value=fill_value, @@ -734,7 +734,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): raise ValueError( f"Unable to fill values because {cls_name} cannot contain NA" ) - taken = self.values.take(indices) + taken = self._values.take(indices) return self._shallow_copy(taken) def _assert_take_fillable( @@ -1988,7 +1988,7 @@ def is_all_dates(self) -> bool: """ Whether or not the index values only consist of dates. """ - return is_datetime_array(ensure_object(self.values)) + return is_datetime_array(ensure_object(self._values)) # -------------------------------------------------------------------- # Pickle Methods @@ -2339,13 +2339,13 @@ def _get_unique_index(self, dropna: bool = False): if self.is_unique and not dropna: return self - values = self.values - if not self.is_unique: values = self.unique() if not isinstance(self, ABCMultiIndex): # extract an array to pass to _shallow_copy values = values._data + else: + values = self._values if dropna: try:
https://api.github.com/repos/pandas-dev/pandas/pulls/33713
2020-04-21T22:46:48Z
2020-04-22T02:24:07Z
2020-04-22T02:24:07Z
2020-04-22T02:49:53Z
TST: prepare for freq-checking in tests.io
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 0811f2f822198..1692e1a8a0dd3 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -407,6 +407,10 @@ def test_mixed(self, frame, path): def test_ts_frame(self, tsframe, path): df = tsframe + # freq doesnt round-trip + index = pd.DatetimeIndex(np.asarray(df.index), freq=None) + df.index = index + df.to_excel(path, "test1") reader = ExcelFile(path) @@ -476,6 +480,11 @@ def test_inf_roundtrip(self, path): tm.assert_frame_equal(df, recons) def test_sheets(self, frame, tsframe, path): + + # freq doesnt round-trip + index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) + tsframe.index = index + frame = frame.copy() frame["A"][:5] = np.nan @@ -581,6 +590,11 @@ def test_excel_roundtrip_indexname(self, merge_cells, path): def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path): # datetime.date, not sure what to test here exactly + + # freq does not round-trip + index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) + tsframe.index = index + tsf = tsframe.copy() tsf.index = [x.date() for x in tsframe.index] diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 0576d8e91d531..137e4c991d080 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -42,6 +42,23 @@ def setup(self): yield + @pytest.fixture + def datetime_series(self): + # Same as usual datetime_series, but with index freq set to None, + # since that doesnt round-trip, see GH#33711 + ser = tm.makeTimeSeries() + ser.name = "ts" + ser.index = ser.index._with_freq(None) + return ser + + @pytest.fixture + def datetime_frame(self): + # Same as usual datetime_frame, but with index freq set to None, + # since that doesnt round-trip, see GH#33711 + df = DataFrame(tm.getTimeSeriesData()) + df.index = df.index._with_freq(None) + return df + def test_frame_double_encoded_labels(self, orient): df = DataFrame( [["a", "b"], ["c", "d"]], @@ -416,6 +433,9 @@ def test_frame_mixedtype_orient(self): # GH10289 tm.assert_frame_equal(left, right) def test_v12_compat(self, datapath): + dti = pd.date_range("2000-01-03", "2000-01-07") + # freq doesnt roundtrip + dti = pd.DatetimeIndex(np.asarray(dti), freq=None) df = DataFrame( [ [1.56808523, 0.65727391, 1.81021139, -0.17251653], @@ -425,7 +445,7 @@ def test_v12_compat(self, datapath): [0.05951614, -2.69652057, 1.28163262, 0.34703478], ], columns=["A", "B", "C", "D"], - index=pd.date_range("2000-01-03", "2000-01-07"), + index=dti, ) df["date"] = pd.Timestamp("19920106 18:21:32.12") df.iloc[3, df.columns.get_loc("date")] = pd.Timestamp("20130101") @@ -444,6 +464,9 @@ def test_v12_compat(self, datapath): def test_blocks_compat_GH9037(self): index = pd.date_range("20000101", periods=10, freq="H") + # freq doesnt round-trip + index = pd.DatetimeIndex(list(index), freq=None) + df_mixed = DataFrame( OrderedDict( float_1=[ diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 34dd9ba9bc7b6..28b043e65b848 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -1011,7 +1011,8 @@ def test_index(self): def test_datetime_index(self): date_unit = "ns" - rng = date_range("1/1/2000", periods=20) + # freq doesnt round-trip + rng = DatetimeIndex(list(date_range("1/1/2000", periods=20)), freq=None) encoded = ujson.encode(rng, date_unit=date_unit) decoded = DatetimeIndex(np.array(ujson.decode(encoded))) diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py index e68dcb3aa577e..d1ed85cc6f466 100644 --- a/pandas/tests/io/parser/test_dtypes.py +++ b/pandas/tests/io/parser/test_dtypes.py @@ -299,7 +299,8 @@ def test_categorical_coerces_numeric(all_parsers): def test_categorical_coerces_datetime(all_parsers): parser = all_parsers - dtype = {"b": CategoricalDtype(pd.date_range("2017", "2019", freq="AS"))} + dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01", "2019-01-01"], freq=None) + dtype = {"b": CategoricalDtype(dti)} data = "b\n2017-01-01\n2018-01-01\n2019-01-01" expected = DataFrame({"b": Categorical(dtype["b"].categories)}) diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 2fcac6fa57cf8..e11bbb89c885c 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -681,8 +681,10 @@ def test_parse_dates_string(all_parsers): """ parser = all_parsers result = parser.read_csv(StringIO(data), index_col="date", parse_dates=["date"]) - index = date_range("1/1/2009", periods=3) - index.name = "date" + # freq doesnt round-trip + index = DatetimeIndex( + list(date_range("1/1/2009", periods=3)), name="date", freq=None + ) expected = DataFrame( {"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]}, index=index @@ -1430,11 +1432,16 @@ def test_parse_timezone(all_parsers): 2018-01-04 09:05:00+09:00,23400""" result = parser.read_csv(StringIO(data), parse_dates=["dt"]) - dti = pd.date_range( - start="2018-01-04 09:01:00", - end="2018-01-04 09:05:00", - freq="1min", - tz=pytz.FixedOffset(540), + dti = pd.DatetimeIndex( + list( + pd.date_range( + start="2018-01-04 09:01:00", + end="2018-01-04 09:05:00", + freq="1min", + tz=pytz.FixedOffset(540), + ), + ), + freq=None, ) expected_data = {"dt": dti, "val": [23350, 23400, 23400, 23400, 23400]} diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 6b6ae8e5f0ca2..299ae2f41d676 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1231,6 +1231,8 @@ def test_append_frame_column_oriented(self, setup_path): # column oriented df = tm.makeTimeDataFrame() + df.index = df.index._with_freq(None) # freq doesnt round-trip + _maybe_remove(store, "df1") store.append("df1", df.iloc[:, :2], axes=["columns"]) store.append("df1", df.iloc[:, 2:]) diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 74d5a77f86827..38d32b0bdc8a3 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -106,17 +106,11 @@ def test_append_with_timezones_dateutil(setup_path): # as index with ensure_clean_store(setup_path) as store: + dti = date_range("2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern")) + dti = dti._with_freq(None) # freq doesnt round-trip + # GH 4098 example - df = DataFrame( - dict( - A=Series( - range(3), - index=date_range( - "2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern") - ), - ) - ) - ) + df = DataFrame(dict(A=Series(range(3), index=dti,))) _maybe_remove(store, "df") store.put("df", df) @@ -199,15 +193,11 @@ def test_append_with_timezones_pytz(setup_path): # as index with ensure_clean_store(setup_path) as store: + dti = date_range("2000-1-1", periods=3, freq="H", tz="US/Eastern") + dti = dti._with_freq(None) # freq doesnt round-trip + # GH 4098 example - df = DataFrame( - dict( - A=Series( - range(3), - index=date_range("2000-1-1", periods=3, freq="H", tz="US/Eastern"), - ) - ) - ) + df = DataFrame(dict(A=Series(range(3), index=dti,))) _maybe_remove(store, "df") store.put("df", df) @@ -258,6 +248,7 @@ def test_timezones_fixed(setup_path): # index rng = date_range("1/1/2000", "1/30/2000", tz="US/Eastern") + rng = rng._with_freq(None) # freq doesnt round-trip df = DataFrame(np.random.randn(len(rng), 4), index=rng) store["df"] = df result = store["df"] @@ -346,6 +337,7 @@ def test_dst_transitions(setup_path): freq="H", ambiguous="infer", ) + times = times._with_freq(None) # freq doesnt round-trip for i in [times, times + pd.Timedelta("10min")]: _maybe_remove(store, "df") diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 0755501ee6285..a2220ceb7feaa 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -63,14 +63,21 @@ def test_basic(self): "bool": [True, False, True], "bool_with_null": [True, np.nan, False], "cat": pd.Categorical(list("abc")), - "dt": pd.date_range("20130101", periods=3), - "dttz": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "dt": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3)), freq=None + ), + "dttz": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3, tz="US/Eastern")), + freq=None, + ), "dt_with_null": [ pd.Timestamp("20130101"), pd.NaT, pd.Timestamp("20130103"), ], - "dtns": pd.date_range("20130101", periods=3, freq="ns"), + "dtns": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3, freq="ns")), freq=None, + ), } ) if pyarrow_version >= LooseVersion("0.16.1.dev"): diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 94cf16c20e6c4..e70a06cc5f582 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -385,6 +385,8 @@ def test_write_index(self, engine): # non-default index for index in indexes: df.index = index + if isinstance(index, pd.DatetimeIndex): + index._set_freq(None) # freq doesnt round-trip check_round_trip(df, engine, check_names=check_names) # index with meta-data @@ -462,7 +464,9 @@ def test_basic(self, pa, df_full): df = df_full # additional supported types for pyarrow - df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="Europe/Brussels") + dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels") + dti._set_freq(None) # freq doesnt round-trip + df["datetime_tz"] = dti df["bool_with_none"] = [True, None, True] check_round_trip(df, pa) @@ -629,7 +633,9 @@ class TestParquetFastParquet(Base): def test_basic(self, fp, df_full): df = df_full - df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="US/Eastern") + dti = pd.date_range("20130101", periods=3, tz="US/Eastern") + dti._set_freq(None) # freq doesnt round-trip + df["datetime_tz"] = dti df["timedelta"] = pd.timedelta_range("1 day", periods=3) check_round_trip(df, fp) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 2f2ae8cd9d32b..70f3f99442183 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1491,7 +1491,7 @@ def test_out_of_bounds_datetime(self): def test_naive_datetimeindex_roundtrip(self): # GH 23510 # Ensure that a naive DatetimeIndex isn't converted to UTC - dates = date_range("2018-01-01", periods=5, freq="6H") + dates = date_range("2018-01-01", periods=5, freq="6H")._with_freq(None) expected = DataFrame({"nums": range(5)}, index=dates) expected.to_sql("foo_table", self.conn, index_label="info_date") result = sql.read_sql_table("foo_table", self.conn, index_col="info_date")
Working on making assert_index_equal check that `freq` attrs match. This ports the necessary test changes from tests.io.
https://api.github.com/repos/pandas-dev/pandas/pulls/33711
2020-04-21T21:17:35Z
2020-04-24T23:22:24Z
2020-04-24T23:22:24Z
2020-04-24T23:24:31Z
DOC: Improve to_parquet documentation
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1bff17b40433d..10382364621c0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2225,6 +2225,16 @@ def to_parquet( col1 col2 0 1 3 1 2 4 + + If you want to get a buffer to the parquet content you can use a io.BytesIO + object, as long as you don't use partition_cols, which creates multiple files. + + >>> import io + >>> f = io.BytesIO() + >>> df.to_parquet(f) + >>> f.seek(0) + 0 + >>> content = f.read() """ from pandas.io.parquet import to_parquet
fixes #29476 - [x] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry / NA
https://api.github.com/repos/pandas-dev/pandas/pulls/33709
2020-04-21T20:03:37Z
2020-05-30T16:32:53Z
2020-05-30T16:32:52Z
2020-06-01T20:05:15Z
TYP: remove #type: ignore for pd.array constructor
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index bf14ed44e3a1c..48f62fe888b9a 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -463,7 +463,7 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: return self return self._set_dtype(dtype) if is_extension_array_dtype(dtype): - return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770 + return array(self, dtype=dtype, copy=copy) if is_integer_dtype(dtype) and self.isna().any(): raise ValueError("Cannot convert float NaN to integer") return np.array(self, dtype=dtype, copy=copy) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 407daf15d5cce..76788f3f97a28 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1,6 +1,6 @@ from datetime import datetime, timedelta import operator -from typing import Any, Sequence, Type, Union, cast +from typing import Any, Sequence, Type, TypeVar, Union, cast import warnings import numpy as np @@ -437,6 +437,9 @@ def _with_freq(self, freq): return self +DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin") + + class DatetimeLikeArrayMixin( ExtensionOpsMixin, AttributesMixin, NDArrayBackedExtensionArray ): @@ -679,7 +682,7 @@ def _concat_same_type(cls, to_concat, axis: int = 0): return cls._simple_new(values, dtype=dtype, freq=new_freq) - def copy(self): + def copy(self: DatetimeLikeArrayT) -> DatetimeLikeArrayT: values = self.asi8.copy() return type(self)._simple_new(values, dtype=self.dtype, freq=self.freq) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 2d9522b00627c..b7dfcd4cb188c 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1,6 +1,6 @@ from datetime import timedelta import operator -from typing import Any, Callable, List, Optional, Sequence, Union +from typing import Any, Callable, List, Optional, Sequence, Type, Union import numpy as np @@ -20,6 +20,7 @@ period_asfreq_arr, ) from pandas._libs.tslibs.timedeltas import Timedelta, delta_to_nanoseconds +from pandas._typing import AnyArrayLike from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( @@ -172,8 +173,8 @@ def _simple_new(cls, values: np.ndarray, freq=None, **kwargs) -> "PeriodArray": @classmethod def _from_sequence( - cls, - scalars: Sequence[Optional[Period]], + cls: Type["PeriodArray"], + scalars: Union[Sequence[Optional[Period]], AnyArrayLike], dtype: Optional[PeriodDtype] = None, copy: bool = False, ) -> "PeriodArray": @@ -186,7 +187,6 @@ def _from_sequence( validate_dtype_freq(scalars.dtype, freq) if copy: scalars = scalars.copy() - assert isinstance(scalars, PeriodArray) # for mypy return scalars periods = np.asarray(scalars, dtype=object) @@ -772,7 +772,7 @@ def raise_on_incompatible(left, right): def period_array( - data: Sequence[Optional[Period]], + data: Union[Sequence[Optional[Period]], AnyArrayLike], freq: Optional[Union[str, Tick]] = None, copy: bool = False, ) -> PeriodArray: diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 2f71f4f4ccc19..351ef1d0429da 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -13,7 +13,7 @@ from pandas._libs import lib from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime -from pandas._typing import ArrayLike, Dtype, DtypeObj +from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -54,7 +54,9 @@ def array( - data: Sequence[object], dtype: Optional[Dtype] = None, copy: bool = True, + data: Union[Sequence[object], AnyArrayLike], + dtype: Optional[Dtype] = None, + copy: bool = True, ) -> "ExtensionArray": """ Create an array.
pandas\core\arrays\categorical.py:481: error: Argument 1 to "array" has incompatible type "Categorical"; expected "Sequence[object]"
https://api.github.com/repos/pandas-dev/pandas/pulls/33706
2020-04-21T19:13:24Z
2020-04-26T21:25:51Z
2020-04-26T21:25:51Z
2020-04-27T07:29:24Z
TYP: remove #type:ignore from core.arrays.datetimelike
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 27b2ed822a49f..3440df4b09c06 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1532,7 +1532,7 @@ def __rsub__(self, other): return -(self - other) - def __iadd__(self, other): # type: ignore + def __iadd__(self, other): result = self + other self[:] = result[:] @@ -1541,7 +1541,7 @@ def __iadd__(self, other): # type: ignore self._freq = result._freq return self - def __isub__(self, other): # type: ignore + def __isub__(self, other): result = self - other self[:] = result[:] diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py index 5c83591b0e71e..515a0a5198d74 100644 --- a/pandas/core/ops/common.py +++ b/pandas/core/ops/common.py @@ -2,13 +2,15 @@ Boilerplate functions used in defining binary operations. """ from functools import wraps +from typing import Callable from pandas._libs.lib import item_from_zerodim +from pandas._typing import F from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries -def unpack_zerodim_and_defer(name: str): +def unpack_zerodim_and_defer(name: str) -> Callable[[F], F]: """ Boilerplate for pandas conventions in arithmetic and comparison methods. @@ -21,7 +23,7 @@ def unpack_zerodim_and_defer(name: str): decorator """ - def wrapper(method): + def wrapper(method: F) -> F: return _unpack_zerodim_and_defer(method, name) return wrapper
pandas\core\arrays\datetimelike.py:1535: error: Signatures of "__iadd__" and "__add__" are incompatible pandas\core\arrays\datetimelike.py:1544: error: Signatures of "__isub__" and "__sub__" are incompatible
https://api.github.com/repos/pandas-dev/pandas/pulls/33705
2020-04-21T19:08:34Z
2020-04-22T03:31:11Z
2020-04-22T03:31:11Z
2020-04-22T11:27:32Z
BUG: DTI/TDI.insert doing invalid casting
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index af5834f01c24c..b32e1516cbbfb 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -857,10 +857,13 @@ def _validate_setitem_value(self, value): def _validate_insert_value(self, value): if isinstance(value, self._recognized_scalars): value = self._scalar_type(value) + self._check_compatible_with(value, setitem=True) + # TODO: if we dont have compat, should we raise or astype(object)? + # PeriodIndex does astype(object) elif is_valid_nat_for_dtype(value, self.dtype): # GH#18295 value = NaT - elif lib.is_scalar(value) and isna(value): + else: raise TypeError( f"cannot insert {type(self).__name__} with incompatible label" ) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 2200eadf3874f..82e6aa9ad1ee6 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -961,37 +961,30 @@ def insert(self, loc, item): ------- new_index : Index """ + if isinstance(item, str): + # TODO: Why are strings special? + # TODO: Should we attempt _scalar_from_string? + return self.astype(object).insert(loc, item) + item = self._data._validate_insert_value(item) freq = None - if isinstance(item, self._data._scalar_type) or item is NaT: - self._data._check_compatible_with(item, setitem=True) - - # check freq can be preserved on edge cases - if self.size and self.freq is not None: + # check freq can be preserved on edge cases + if self.freq is not None: + if self.size: if item is NaT: pass elif (loc == 0 or loc == -len(self)) and item + self.freq == self[0]: freq = self.freq elif (loc == len(self)) and item - self.freq == self[-1]: freq = self.freq - elif self.freq is not None: + else: # Adding a single item to an empty index may preserve freq if self.freq.is_on_offset(item): freq = self.freq - item = item.asm8 - try: - new_i8s = np.concatenate( - (self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8) - ) - arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) - return type(self)._simple_new(arr, name=self.name) - except (AttributeError, TypeError) as err: + item = self._data._unbox_scalar(item) - # fall back to object index - if isinstance(item, str): - return self.astype(object).insert(loc, item) - raise TypeError( - f"cannot insert {type(self).__name__} with incompatible label" - ) from err + new_i8s = np.concatenate([self[:loc].asi8, [item], self[loc:].asi8]) + arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) + return type(self)._simple_new(arr, name=self.name) diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py index 034e1c6a4e1b0..b4f6cc3798f4f 100644 --- a/pandas/tests/indexes/datetimes/test_insert.py +++ b/pandas/tests/indexes/datetimes/test_insert.py @@ -165,3 +165,26 @@ def test_insert(self): assert result.name == expected.name assert result.tz == expected.tz assert result.freq is None + + @pytest.mark.parametrize( + "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)] + ) + def test_insert_mismatched_types_raises(self, tz_aware_fixture, item): + # GH#33703 dont cast these to dt64 + tz = tz_aware_fixture + dti = date_range("2019-11-04", periods=9, freq="-1D", name=9, tz=tz) + + msg = "incompatible label" + with pytest.raises(TypeError, match=msg): + dti.insert(1, item) + + def test_insert_object_casting(self, tz_aware_fixture): + # GH#33703 + tz = tz_aware_fixture + dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz) + + # ATM we treat this as a string, but we could plausibly wrap it in Timestamp + value = "2019-11-05" + result = dti.insert(0, value) + expected = Index(["2019-11-05"] + list(dti), dtype=object, name=9) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/test_insert.py index e65c871428bab..1ebc0a4b1eca0 100644 --- a/pandas/tests/indexes/timedeltas/test_insert.py +++ b/pandas/tests/indexes/timedeltas/test_insert.py @@ -82,6 +82,17 @@ def test_insert_invalid_na(self): with pytest.raises(TypeError, match="incompatible label"): idx.insert(0, np.datetime64("NaT")) + @pytest.mark.parametrize( + "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")] + ) + def test_insert_mismatched_types_raises(self, item): + # GH#33703 dont cast these to td64 + tdi = TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + msg = "incompatible label" + with pytest.raises(TypeError, match=msg): + tdi.insert(1, item) + def test_insert_dont_cast_strings(self): # To match DatetimeIndex and PeriodIndex behavior, dont try to # parse strings to Timedelta diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 6cb73823adabb..07dd8eac4fbe0 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -447,7 +447,7 @@ def test_insert_index_datetimes(self, fill_val, exp_dtype): with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo")) - msg = "cannot insert DatetimeIndex with incompatible label" + msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1) @@ -464,12 +464,12 @@ def test_insert_index_timedelta64(self): ) # ToDo: must coerce to object - msg = "cannot insert TimedeltaIndex with incompatible label" + msg = "cannot insert TimedeltaArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01")) # ToDo: must coerce to object - msg = "cannot insert TimedeltaIndex with incompatible label" + msg = "cannot insert TimedeltaArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1) diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 6c259db33cf7c..ee87a3f9f5ecd 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -335,7 +335,7 @@ def test_partial_set_invalid(self): df = orig.copy() # don't allow not string inserts - msg = "cannot insert DatetimeIndex with incompatible label" + msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): df.loc[100.0, :] = df.iloc[0]
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33703
2020-04-21T15:28:51Z
2020-04-25T23:54:30Z
2020-04-25T23:54:30Z
2020-04-26T00:32:44Z
BUG: Fix memory issues in rolling.min/max
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index f85dc83ab8605..e3c9c7ccdc51c 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -150,19 +150,18 @@ def time_quantile(self, constructor, window, dtype, percentile, interpolation): self.roll.quantile(percentile, interpolation=interpolation) -class PeakMemFixed: - def setup(self): - N = 10 - arr = 100 * np.random.random(N) - self.roll = pd.Series(arr).rolling(10) - - def peakmem_fixed(self): - # GH 25926 - # This is to detect memory leaks in rolling operations. - # To save time this is only ran on one method. - # 6000 iterations is enough for most types of leaks to be detected - for x in range(6000): - self.roll.max() +class PeakMemFixedWindowMinMax: + + params = ["min", "max"] + + def setup(self, operation): + N = int(1e6) + arr = np.random.random(N) + self.roll = pd.Series(arr).rolling(2) + + def peakmem_fixed(self, operation): + for x in range(5): + getattr(self.roll, operation)() class ForwardWindowMethods: diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 07849702c646d..43bf0e82490e2 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -608,6 +608,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.resample` where an ``AmbiguousTimeError`` would be raised when the resulting timezone aware :class:`DatetimeIndex` had a DST transition at midnight (:issue:`25758`) - Bug in :meth:`DataFrame.groupby` where a ``ValueError`` would be raised when grouping by a categorical column with read-only categories and ``sort=False`` (:issue:`33410`) - Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`) +- Bug in :meth:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`) Reshaping ^^^^^^^^^ diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 673820fd8464a..afa0539014041 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -971,8 +971,8 @@ cdef inline numeric calc_mm(int64_t minp, Py_ssize_t nobs, return result -def roll_max_fixed(ndarray[float64_t] values, ndarray[int64_t] start, - ndarray[int64_t] end, int64_t minp, int64_t win): +def roll_max_fixed(float64_t[:] values, int64_t[:] start, + int64_t[:] end, int64_t minp, int64_t win): """ Moving max of 1d array of any numeric type along axis=0 ignoring NaNs. @@ -988,7 +988,7 @@ def roll_max_fixed(ndarray[float64_t] values, ndarray[int64_t] start, make the interval closed on the right, left, both or neither endpoints """ - return _roll_min_max_fixed(values, start, end, minp, win, is_max=1) + return _roll_min_max_fixed(values, minp, win, is_max=1) def roll_max_variable(ndarray[float64_t] values, ndarray[int64_t] start, @@ -1011,8 +1011,8 @@ def roll_max_variable(ndarray[float64_t] values, ndarray[int64_t] start, return _roll_min_max_variable(values, start, end, minp, is_max=1) -def roll_min_fixed(ndarray[float64_t] values, ndarray[int64_t] start, - ndarray[int64_t] end, int64_t minp, int64_t win): +def roll_min_fixed(float64_t[:] values, int64_t[:] start, + int64_t[:] end, int64_t minp, int64_t win): """ Moving min of 1d array of any numeric type along axis=0 ignoring NaNs. @@ -1025,7 +1025,7 @@ def roll_min_fixed(ndarray[float64_t] values, ndarray[int64_t] start, index : ndarray, optional index for window computation """ - return _roll_min_max_fixed(values, start, end, minp, win, is_max=0) + return _roll_min_max_fixed(values, minp, win, is_max=0) def roll_min_variable(ndarray[float64_t] values, ndarray[int64_t] start, @@ -1112,9 +1112,7 @@ cdef _roll_min_max_variable(ndarray[numeric] values, return output -cdef _roll_min_max_fixed(ndarray[numeric] values, - ndarray[int64_t] starti, - ndarray[int64_t] endi, +cdef _roll_min_max_fixed(numeric[:] values, int64_t minp, int64_t win, bint is_max):
This fixes at least the reproducible part of #30726. I am not totally sure what is going on here (is this a true memory leak?), and whether this fixes all issues, but it does strongly reduce memory usage as measured by `psutil`. My tests have shown that there are two solutions that avoid growing memory usage: - pass memoryviews (`float64_t[:]`) instead of `ndarray[float64_t]` - remove `starti` and `endi` as arguments to `_roll_min_max_fixed` This commit implements both, since `_roll_min_max_fixed` doesn't use `starti` and `endi` anyways. - [x] fixes at least part of closes #30726 closes #32466 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I am unsure about testing: Does this need a test? If so, what would be a good way to go about testing? The tests I performed (example code in the linked issue) are probably very system specific.
https://api.github.com/repos/pandas-dev/pandas/pulls/33693
2020-04-21T07:52:23Z
2020-04-28T14:48:42Z
2020-04-28T14:48:41Z
2020-05-26T09:32:45Z
CLN: remove shallow_copy_with_infer
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 530aaee24c7fb..62842e7286539 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -270,10 +270,6 @@ def _outer_indexer(self, left, right): # would we like our indexing holder to defer to us _defer_to_indexing = False - # prioritize current class for _shallow_copy_with_infer, - # used to infer integers as datetime-likes - _infer_as_myclass = False - _engine_type = libindex.ObjectEngine # whether we support partial string indexing. Overridden # in DatetimeIndex and PeriodIndex @@ -441,10 +437,6 @@ def __new__( _simple_new), but fills caller's metadata otherwise specified. Passed kwargs will overwrite corresponding metadata. - - _shallow_copy_with_infer: It returns new Index inferring its type - from passed values. It fills caller's metadata otherwise specified as the - same as _shallow_copy. - See each method's docstring. """ @@ -517,35 +509,6 @@ def _shallow_copy(self, values=None, name: Label = no_default): result._cache = cache return result - def _shallow_copy_with_infer(self, values, **kwargs): - """ - Create a new Index inferring the class with passed value, don't copy - the data, use the same object attributes with passed in attributes - taking precedence. - - *this is an internal non-public method* - - Parameters - ---------- - values : the values to create the new Index, optional - kwargs : updates the default attributes for this Index - """ - attributes = self._get_attributes_dict() - attributes.update(kwargs) - attributes["copy"] = False - if not len(values) and "dtype" not in kwargs: - # TODO: what if hasattr(values, "dtype")? - attributes["dtype"] = self.dtype - if self._infer_as_myclass: - try: - return self._constructor(values, **attributes) - except (TypeError, ValueError): - pass - - # Remove tz so Index will try non-DatetimeIndex inference - attributes.pop("tz", None) - return Index(values, **attributes) - def is_(self, other) -> bool: """ More flexible, faster check like ``is`` but that works through views. @@ -2810,11 +2773,7 @@ def symmetric_difference(self, other, result_name=None, sort=None): except TypeError: pass - attribs = self._get_attributes_dict() - attribs["name"] = result_name - if "freq" in attribs: - attribs["freq"] = None - return self._shallow_copy_with_infer(the_diff, **attribs) + return Index(the_diff, dtype=self.dtype, name=result_name) def _assert_can_do_setop(self, other): if not is_list_like(other): @@ -3388,7 +3347,7 @@ def _reindex_non_unique(self, target): new_indexer = np.arange(len(self.take(indexer))) new_indexer[~check] = -1 - new_index = self._shallow_copy_with_infer(new_labels) + new_index = Index(new_labels, name=self.name) return new_index, indexer, new_indexer # -------------------------------------------------------------------- @@ -3945,7 +3904,7 @@ def where(self, cond, other=None): # it's float) if there are NaN values in our output. dtype = None - return self._shallow_copy_with_infer(values, dtype=dtype) + return Index(values, dtype=dtype, name=self.name) # construction helpers @classmethod @@ -4175,7 +4134,8 @@ def _concat_same_dtype(self, to_concat, name): to_concat = [x._values if isinstance(x, Index) else x for x in to_concat] - return self._shallow_copy_with_infer(np.concatenate(to_concat), **attribs) + res_values = np.concatenate(to_concat) + return Index(res_values, name=name) def putmask(self, mask, value): """ @@ -5217,7 +5177,7 @@ def insert(self, loc: int, item): arr = np.asarray(self) item = self._coerce_scalar_to_index(item)._values idx = np.concatenate((arr[:loc], item, arr[loc:])) - return self._shallow_copy_with_infer(idx) + return Index(idx, name=self.name) def drop(self, labels, errors: str_t = "raise"): """ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index ba1a9a4e08fa0..0cf6698d316bb 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -690,7 +690,8 @@ def map(self, mapper): >>> idx.map({'a': 'first', 'b': 'second'}) Index(['first', 'second', nan], dtype='object') """ - return self._shallow_copy_with_infer(self._values.map(mapper)) + mapped = self._values.map(mapper) + return Index(mapped, name=self.name) def delete(self, loc): """ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 1ec6cf8fd7b4e..649d4e6dfc384 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -214,7 +214,6 @@ class DatetimeIndex(DatetimeTimedeltaMixin): _attributes = ["name", "tz", "freq"] _is_numeric_dtype = False - _infer_as_myclass = True _data: DatetimeArray tz: Optional[tzinfo] diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 42e0d228dab09..52439a1ea3946 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1046,16 +1046,17 @@ def _shallow_copy( result._cache.pop("levels", None) # GH32669 return result - def _shallow_copy_with_infer(self, values, **kwargs): - # On equal MultiIndexes the difference is empty. + def symmetric_difference(self, other, result_name=None, sort=None): + # On equal symmetric_difference MultiIndexes the difference is empty. # Therefore, an empty MultiIndex is returned GH13490 - if len(values) == 0: + tups = Index.symmetric_difference(self, other, result_name, sort) + if len(tups) == 0: return MultiIndex( levels=[[] for _ in range(self.nlevels)], codes=[[] for _ in range(self.nlevels)], - **kwargs, + names=tups.name, ) - return self._shallow_copy(values, **kwargs) + return type(self).from_tuples(tups, names=tups.name) # -------------------------------------------------------------------- diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 1f565828ec7a5..ece656679688f 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -148,7 +148,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # define my properties & methods for delegation _is_numeric_dtype = False - _infer_as_myclass = True _data: PeriodArray freq: DateOffset diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 765b948f13e96..4caf9107808ed 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -121,7 +121,6 @@ class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): _comparables = ["name", "freq"] _attributes = ["name", "freq"] _is_numeric_dtype = True - _infer_as_myclass = True _data: TimedeltaArray diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index f4eb16602f8a0..72831b29af61e 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -188,7 +188,7 @@ def to_numeric(arg, errors="raise", downcast=None): return pd.Series(values, index=arg.index, name=arg.name) elif is_index: # because we want to coerce to numeric if possible, - # do not use _shallow_copy_with_infer + # do not use _shallow_copy return pd.Index(values, name=arg.name) elif is_scalars: return values[0]
https://api.github.com/repos/pandas-dev/pandas/pulls/33691
2020-04-21T01:57:46Z
2020-04-22T02:31:37Z
2020-04-22T02:31:37Z
2020-04-22T02:48:25Z
CLN: Split dtype inference tests
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 3d58df258e8e9..8c0580b7cf047 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -782,108 +782,91 @@ def test_datetime(self): index = Index(dates) assert index.inferred_type == "datetime64" - def test_infer_dtype_datetime(self): - - arr = np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - + def test_infer_dtype_datetime64(self): arr = np.array( [np.datetime64("2011-01-01"), np.datetime64("2011-01-01")], dtype=object ) assert lib.infer_dtype(arr, skipna=True) == "datetime64" - arr = np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + def test_infer_dtype_datetime64_with_na(self, na_value): # starts with nan - for n in [pd.NaT, np.nan]: - arr = np.array([n, pd.Timestamp("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - - arr = np.array([n, np.datetime64("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "datetime64" - - arr = np.array([n, datetime(2011, 1, 1)]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - - arr = np.array([n, pd.Timestamp("2011-01-02"), n]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - - arr = np.array([n, np.datetime64("2011-01-02"), n]) - assert lib.infer_dtype(arr, skipna=True) == "datetime64" - - arr = np.array([n, datetime(2011, 1, 1), n]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" + arr = np.array([na_value, np.datetime64("2011-01-02")]) + assert lib.infer_dtype(arr, skipna=True) == "datetime64" - # different type of nat - arr = np.array( - [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object - ) - assert lib.infer_dtype(arr, skipna=False) == "mixed" + arr = np.array([na_value, np.datetime64("2011-01-02"), na_value]) + assert lib.infer_dtype(arr, skipna=True) == "datetime64" - arr = np.array( - [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object - ) + @pytest.mark.parametrize( + "arr", + [ + np.array( + [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object + ), + np.array( + [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object + ), + np.array([np.datetime64("2011-01-01"), pd.Timestamp("2011-01-02")]), + np.array([pd.Timestamp("2011-01-02"), np.datetime64("2011-01-01")]), + np.array([np.nan, pd.Timestamp("2011-01-02"), 1.1]), + np.array([np.nan, "2011-01-01", pd.Timestamp("2011-01-02")]), + np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object), + np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object), + ], + ) + def test_infer_datetimelike_dtype_mixed(self, arr): assert lib.infer_dtype(arr, skipna=False) == "mixed" - # mixed datetime - arr = np.array([datetime(2011, 1, 1), pd.Timestamp("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "datetime" - - # should be datetime? - arr = np.array([np.datetime64("2011-01-01"), pd.Timestamp("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "mixed" - - arr = np.array([pd.Timestamp("2011-01-02"), np.datetime64("2011-01-01")]) - assert lib.infer_dtype(arr, skipna=True) == "mixed" - + def test_infer_dtype_mixed_integer(self): arr = np.array([np.nan, pd.Timestamp("2011-01-02"), 1]) assert lib.infer_dtype(arr, skipna=True) == "mixed-integer" - arr = np.array([np.nan, pd.Timestamp("2011-01-02"), 1.1]) - assert lib.infer_dtype(arr, skipna=True) == "mixed" + @pytest.mark.parametrize( + "arr", + [ + np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]), + np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]), + np.array([datetime(2011, 1, 1), pd.Timestamp("2011-01-02")]), + ], + ) + def test_infer_dtype_datetime(self, arr): + assert lib.infer_dtype(arr, skipna=True) == "datetime" - arr = np.array([np.nan, "2011-01-01", pd.Timestamp("2011-01-02")]) - assert lib.infer_dtype(arr, skipna=True) == "mixed" + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + @pytest.mark.parametrize( + "time_stamp", [pd.Timestamp("2011-01-01"), datetime(2011, 1, 1)] + ) + def test_infer_dtype_datetime_with_na(self, na_value, time_stamp): + # starts with nan + arr = np.array([na_value, time_stamp]) + assert lib.infer_dtype(arr, skipna=True) == "datetime" - def test_infer_dtype_timedelta(self): + arr = np.array([na_value, time_stamp, na_value]) + assert lib.infer_dtype(arr, skipna=True) == "datetime" - arr = np.array([pd.Timedelta("1 days"), pd.Timedelta("2 days")]) + @pytest.mark.parametrize( + "arr", + [ + np.array([pd.Timedelta("1 days"), pd.Timedelta("2 days")]), + np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object), + np.array([timedelta(1), timedelta(2)]), + ], + ) + def test_infer_dtype_timedelta(self, arr): assert lib.infer_dtype(arr, skipna=True) == "timedelta" - arr = np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object) + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + @pytest.mark.parametrize( + "delta", [Timedelta("1 days"), np.timedelta64(1, "D"), timedelta(1)] + ) + def test_infer_dtype_timedelta_with_na(self, na_value, delta): + # starts with nan + arr = np.array([na_value, delta]) assert lib.infer_dtype(arr, skipna=True) == "timedelta" - arr = np.array([timedelta(1), timedelta(2)]) + arr = np.array([na_value, delta, na_value]) assert lib.infer_dtype(arr, skipna=True) == "timedelta" - # starts with nan - for n in [pd.NaT, np.nan]: - arr = np.array([n, Timedelta("1 days")]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - arr = np.array([n, np.timedelta64(1, "D")]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - arr = np.array([n, timedelta(1)]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - arr = np.array([n, pd.Timedelta("1 days"), n]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - arr = np.array([n, np.timedelta64(1, "D"), n]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - arr = np.array([n, timedelta(1), n]) - assert lib.infer_dtype(arr, skipna=True) == "timedelta" - - # different type of nat - arr = np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object) - assert lib.infer_dtype(arr, skipna=False) == "mixed" - - arr = np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object) - assert lib.infer_dtype(arr, skipna=False) == "mixed" - def test_infer_dtype_period(self): # GH 13664 arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="D")]) @@ -892,25 +875,26 @@ def test_infer_dtype_period(self): arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="M")]) assert lib.infer_dtype(arr, skipna=True) == "period" - # starts with nan - for n in [pd.NaT, np.nan]: - arr = np.array([n, pd.Period("2011-01", freq="D")]) - assert lib.infer_dtype(arr, skipna=True) == "period" - - arr = np.array([n, pd.Period("2011-01", freq="D"), n]) - assert lib.infer_dtype(arr, skipna=True) == "period" - - # different type of nat + def test_infer_dtype_period_mixed(self): arr = np.array( - [np.datetime64("nat"), pd.Period("2011-01", freq="M")], dtype=object + [pd.Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object ) assert lib.infer_dtype(arr, skipna=False) == "mixed" arr = np.array( - [pd.Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object + [np.datetime64("nat"), pd.Period("2011-01", freq="M")], dtype=object ) assert lib.infer_dtype(arr, skipna=False) == "mixed" + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + def test_infer_dtype_period_with_na(self, na_value): + # starts with nan + arr = np.array([na_value, pd.Period("2011-01", freq="D")]) + assert lib.infer_dtype(arr, skipna=True) == "period" + + arr = np.array([na_value, pd.Period("2011-01", freq="D"), na_value]) + assert lib.infer_dtype(arr, skipna=True) == "period" + @pytest.mark.parametrize( "data", [
Breaking up some very large tests in dtypes/test_inference.py
https://api.github.com/repos/pandas-dev/pandas/pulls/33690
2020-04-21T00:28:15Z
2020-04-21T12:41:01Z
2020-04-21T12:41:01Z
2020-04-21T12:51:03Z
fixing highly confusing typo.
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index f30d6c9d5d4c0..7f8d0e529fc8b 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -727,7 +727,7 @@ You can use the ``labels`` and ``colors`` keywords to specify the labels and col .. warning:: - Most pandas plots use the the ``label`` and ``color`` arguments (not the lack of "s" on those). + Most pandas plots use the the ``label`` and ``color`` arguments (note the lack of "s" on those). To be consistent with :func:`matplotlib.pyplot.pie` you must use ``labels`` and ``colors``. If you want to hide wedge labels, specify ``labels=None``.
The power of an 'e'.
https://api.github.com/repos/pandas-dev/pandas/pulls/9074
2014-12-14T06:05:46Z
2014-12-14T21:50:02Z
2014-12-14T21:50:02Z
2014-12-14T22:14:09Z
ENH: add interval kwarg to get_data_yahoo issue #9071
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 21b1ddea0e9da..8e67b3c067367 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -57,6 +57,7 @@ Enhancements .. _whatsnew_0160.enhancements: - Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`) +- Added time interval selection in get_data_yahoo (:issue:`9071`) Performance ~~~~~~~~~~~ diff --git a/pandas/io/data.py b/pandas/io/data.py index 3d92d383badf8..b5cf5f9d9be19 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -180,7 +180,7 @@ def _retry_read_url(url, retry_count, pause, name): _HISTORICAL_YAHOO_URL = 'http://ichart.finance.yahoo.com/table.csv?' -def _get_hist_yahoo(sym, start, end, retry_count, pause): +def _get_hist_yahoo(sym, start, end, interval, retry_count, pause): """ Get historical data for the given name from yahoo. Date format is datetime @@ -195,7 +195,7 @@ def _get_hist_yahoo(sym, start, end, retry_count, pause): '&d=%s' % (end.month - 1) + '&e=%s' % end.day + '&f=%s' % end.year + - '&g=d' + + '&g=%s' % interval + '&ignore=.csv') return _retry_read_url(url, retry_count, pause, 'Yahoo!') @@ -203,7 +203,7 @@ def _get_hist_yahoo(sym, start, end, retry_count, pause): _HISTORICAL_GOOGLE_URL = 'http://www.google.com/finance/historical?' -def _get_hist_google(sym, start, end, retry_count, pause): +def _get_hist_google(sym, start, end, interval, retry_count, pause): """ Get historical data for the given name from google. Date format is datetime @@ -314,14 +314,14 @@ def get_components_yahoo(idx_sym): return idx_df -def _dl_mult_symbols(symbols, start, end, chunksize, retry_count, pause, +def _dl_mult_symbols(symbols, start, end, interval, chunksize, retry_count, pause, method): stocks = {} failed = [] for sym_group in _in_chunks(symbols, chunksize): for sym in sym_group: try: - stocks[sym] = method(sym, start, end, retry_count, pause) + stocks[sym] = method(sym, start, end, interval, retry_count, pause) except IOError: warnings.warn('Failed to read symbol: {0!r}, replacing with ' 'NaN.'.format(sym), SymbolWarning) @@ -343,20 +343,20 @@ def _dl_mult_symbols(symbols, start, end, chunksize, retry_count, pause, _source_functions = {'google': _get_hist_google, 'yahoo': _get_hist_yahoo} -def _get_data_from(symbols, start, end, retry_count, pause, adjust_price, +def _get_data_from(symbols, start, end, interval, retry_count, pause, adjust_price, ret_index, chunksize, source): src_fn = _source_functions[source] # If a single symbol, (e.g., 'GOOG') if isinstance(symbols, (compat.string_types, int)): - hist_data = src_fn(symbols, start, end, retry_count, pause) + hist_data = src_fn(symbols, start, end, interval, retry_count, pause) # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT']) elif isinstance(symbols, DataFrame): - hist_data = _dl_mult_symbols(symbols.index, start, end, chunksize, + hist_data = _dl_mult_symbols(symbols.index, start, end, interval, chunksize, retry_count, pause, src_fn) else: - hist_data = _dl_mult_symbols(symbols, start, end, chunksize, + hist_data = _dl_mult_symbols(symbols, start, end, interval, chunksize, retry_count, pause, src_fn) if source.lower() == 'yahoo': if ret_index: @@ -369,7 +369,7 @@ def _get_data_from(symbols, start, end, retry_count, pause, adjust_price, def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3, pause=0.001, adjust_price=False, ret_index=False, - chunksize=25): + chunksize=25, interval='d'): """ Returns DataFrame/Panel of historical stock prices from symbols, over date range, start to end. To avoid being penalized by Yahoo! Finance servers, @@ -398,12 +398,17 @@ def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3, If True, includes a simple return index 'Ret_Index' in hist_data. chunksize : int, default 25 Number of symbols to download consecutively before intiating pause. + interval : string, default 'd' + Time interval code, valid values are 'd' for daily, 'w' for weekly, + 'm' for monthly and 'v' for dividend. Returns ------- hist_data : DataFrame (str) or Panel (array-like object, DataFrame) """ - return _get_data_from(symbols, start, end, retry_count, pause, + if interval not in ['d', 'w', 'm', 'v']: + raise ValueError("Invalid interval: valid values are 'd', 'w', 'm' and 'v'") + return _get_data_from(symbols, start, end, interval, retry_count, pause, adjust_price, ret_index, chunksize, 'yahoo') @@ -437,7 +442,7 @@ def get_data_google(symbols=None, start=None, end=None, retry_count=3, ------- hist_data : DataFrame (str) or Panel (array-like object, DataFrame) """ - return _get_data_from(symbols, start, end, retry_count, pause, + return _get_data_from(symbols, start, end, None, retry_count, pause, adjust_price, ret_index, chunksize, 'google') diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index a65722dc76556..2d6f14c79633a 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -213,6 +213,27 @@ def test_get_data_single_symbol(self): # just test that we succeed web.get_data_yahoo('GOOG') + @network + def test_get_data_interval(self): + # daily interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='d') + self.assertEqual(len(pan), 252) + + # weekly interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='w') + self.assertEqual(len(pan), 53) + + # montly interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='m') + self.assertEqual(len(pan), 12) + + # dividend data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='v') + self.assertEqual(len(pan), 4) + + # test fail on invalid interval + self.assertRaises(ValueError, web.get_data_yahoo, 'XOM', interval='NOT VALID') + @network def test_get_data_multiple_symbols(self): # just test that we succeed
PR for the issue #9071
https://api.github.com/repos/pandas-dev/pandas/pulls/9072
2014-12-13T19:30:10Z
2015-01-05T23:49:33Z
2015-01-05T23:49:33Z
2015-01-05T23:50:25Z
pivot & unstack with nan in the index
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 7433adaa4b738..66b772d35f2e2 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -67,6 +67,7 @@ Bug Fixes - Bug in ``MultiIndex.has_duplicates`` when having many levels causes an indexer overflow (:issue:`9075`) +- Bug in ``pivot`` and `unstack`` where ``nan`` values would break index alignment (:issue:`7466`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4c221cc27fdce..888dca3914b53 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -6,7 +6,7 @@ from pandas.compat import( zip, builtins, range, long, lzip, - OrderedDict, callable + OrderedDict, callable, filter, map ) from pandas import compat @@ -3510,6 +3510,61 @@ def get_group_index(label_list, shape): np.putmask(group_index, mask, -1) return group_index + +def get_flat_ids(labels, shape, retain_lex_rank): + """ + Given a list of labels at each level, returns a flat array of int64 ids + corresponding to unique tuples across the labels. If `retain_lex_rank`, + rank of returned ids preserve lexical ranks of labels. + + Parameters + ---------- + labels: sequence of arrays + Integers identifying levels at each location + shape: sequence of ints same length as labels + Number of unique levels at each location + retain_lex_rank: boolean + If the ranks of returned ids should match lexical ranks of labels + + Returns + ------- + An array of type int64 where two elements are equal if their corresponding + labels are equal at all location. + """ + def loop(labels, shape): + # how many levels can be done without overflow: + pred = lambda i: not _int64_overflow_possible(shape[:i]) + nlev = next(filter(pred, range(len(shape), 0, -1))) + + # compute flat ids for the first `nlev` levels + stride = np.prod(shape[1:nlev], dtype='i8') + out = stride * labels[0].astype('i8', subok=False, copy=False) + + for i in range(1, nlev): + stride //= shape[i] + out += labels[i] * stride + + if nlev == len(shape): # all levels done! + return out + + # compress what has been done so far in order to avoid overflow + # to retain lexical ranks, obs_ids should be sorted + comp_ids, obs_ids = _compress_group_index(out, sort=retain_lex_rank) + + labels = [comp_ids] + labels[nlev:] + shape = [len(obs_ids)] + shape[nlev:] + + return loop(labels, shape) + + def maybe_lift(lab, size): # pormote nan values + return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) + + labels = map(com._ensure_int64, labels) + labels, shape = map(list, zip(*map(maybe_lift, labels, shape))) + + return loop(labels, shape) + + _INT64_MAX = np.iinfo(np.int64).max diff --git a/pandas/core/index.py b/pandas/core/index.py index d2a3093e686a7..97890299657cf 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -3226,44 +3226,13 @@ def _has_complex_internals(self): @cache_readonly def is_unique(self): from pandas.hashtable import Int64HashTable - - def _get_group_index(labels, shape): - from pandas.core.groupby import _int64_overflow_possible, \ - _compress_group_index - - # how many levels can be done without overflow - pred = lambda i: not _int64_overflow_possible(shape[:i]) - nlev = next(filter(pred, range(len(shape), 0, -1))) - - # compute group indicies for the first `nlev` levels - group_index = labels[0].astype('i8', subok=False, copy=True) - stride = shape[0] - - for i in range(1, nlev): - group_index += labels[i] * stride - stride *= shape[i] - - if nlev == len(shape): - return group_index - - comp_ids, obs_ids = _compress_group_index(group_index, sort=False) - - labels = [comp_ids] + labels[nlev:] - shape = [len(obs_ids)] + shape[nlev:] - - return _get_group_index(labels, shape) - - def _maybe_lift(lab, size): # pormote nan values - return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) + from pandas.core.groupby import get_flat_ids shape = map(len, self.levels) - labels = map(_ensure_int64, self.labels) - - labels, shape = map(list, zip(*map(_maybe_lift, labels, shape))) - group_index = _get_group_index(labels, shape) + ids = get_flat_ids(self.labels, shape, False) + table = Int64HashTable(min(1 << 20, len(ids))) - table = Int64HashTable(min(1 << 20, len(group_index))) - return len(table.unique(group_index)) == len(self) + return len(table.unique(ids)) == len(self) def get_value(self, series, key): # somewhat broken encapsulation diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py index 5ed823d690028..19208506fdc72 100644 --- a/pandas/core/reshape.py +++ b/pandas/core/reshape.py @@ -82,18 +82,10 @@ def __init__(self, values, index, level=-1, value_columns=None): self.level = self.index._get_level_number(level) - levels = index.levels - labels = index.labels - - def _make_index(lev, lab): - values = _make_index_array_level(lev.values, lab) - i = lev._simple_new(values, lev.name, - freq=getattr(lev, 'freq', None), - tz=getattr(lev, 'tz', None)) - return i - - self.new_index_levels = [_make_index(lev, lab) - for lev, lab in zip(levels, labels)] + # when index includes `nan`, need to lift levels/strides by 1 + self.lift = 1 if -1 in self.index.labels[self.level] else 0 + + self.new_index_levels = list(index.levels) self.new_index_names = list(index.names) self.removed_name = self.new_index_names.pop(self.level) @@ -134,10 +126,10 @@ def _make_selectors(self): ngroups = len(obs_ids) comp_index = _ensure_platform_int(comp_index) - stride = self.index.levshape[self.level] + stride = self.index.levshape[self.level] + self.lift self.full_shape = ngroups, stride - selector = self.sorted_labels[-1] + stride * comp_index + selector = self.sorted_labels[-1] + stride * comp_index + self.lift mask = np.zeros(np.prod(self.full_shape), dtype=bool) mask.put(selector, True) @@ -166,20 +158,6 @@ def get_result(self): values = com.take_nd(values, inds, axis=1) columns = columns[inds] - # we might have a missing index - if len(index) != values.shape[0]: - mask = isnull(index) - if mask.any(): - l = np.arange(len(index)) - values, orig_values = (np.empty((len(index), values.shape[1])), - values) - values.fill(np.nan) - values_indexer = com._ensure_int64(l[~mask]) - for i, j in enumerate(values_indexer): - values[j] = orig_values[i] - else: - index = index.take(self.unique_groups) - # may need to coerce categoricals here if self.is_categorical is not None: values = [ Categorical.from_array(values[:,i], @@ -220,9 +198,16 @@ def get_new_values(self): def get_new_columns(self): if self.value_columns is None: - return self.removed_level + if self.lift == 0: + return self.removed_level + + lev = self.removed_level + vals = np.insert(lev.astype('object'), 0, + _get_na_value(lev.dtype.type)) + + return lev._shallow_copy(vals) - stride = len(self.removed_level) + stride = len(self.removed_level) + self.lift width = len(self.value_columns) propagator = np.repeat(np.arange(width), stride) if isinstance(self.value_columns, MultiIndex): @@ -231,59 +216,34 @@ def get_new_columns(self): new_labels = [lab.take(propagator) for lab in self.value_columns.labels] - new_labels.append(np.tile(np.arange(stride), width)) else: new_levels = [self.value_columns, self.removed_level] new_names = [self.value_columns.name, self.removed_name] + new_labels = [propagator] - new_labels = [] - - new_labels.append(propagator) - new_labels.append(np.tile(np.arange(stride), width)) - + new_labels.append(np.tile(np.arange(stride) - self.lift, width)) return MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) def get_new_index(self): - result_labels = [] - for cur in self.sorted_labels[:-1]: - labels = cur.take(self.compressor) - labels = _make_index_array_level(labels, cur) - result_labels.append(labels) + result_labels = [lab.take(self.compressor) + for lab in self.sorted_labels[:-1]] # construct the new index if len(self.new_index_levels) == 1: - new_index = self.new_index_levels[0] - new_index.name = self.new_index_names[0] - else: - new_index = MultiIndex(levels=self.new_index_levels, - labels=result_labels, - names=self.new_index_names, - verify_integrity=False) - - return new_index + lev, lab = self.new_index_levels[0], result_labels[0] + if not (lab == -1).any(): + return lev.take(lab) + vals = np.insert(lev.astype('object'), len(lev), + _get_na_value(lev.dtype.type)).take(lab) -def _make_index_array_level(lev, lab): - """ create the combined index array, preserving nans, return an array """ - mask = lab == -1 - if not mask.any(): - return lev - - l = np.arange(len(lab)) - mask_labels = np.empty(len(mask[mask]), dtype=object) - mask_labels.fill(_get_na_value(lev.dtype.type)) - mask_indexer = com._ensure_int64(l[mask]) - - labels = lev - labels_indexer = com._ensure_int64(l[~mask]) - - new_labels = np.empty(tuple([len(lab)]), dtype=object) - new_labels[labels_indexer] = labels - new_labels[mask_indexer] = mask_labels - - return new_labels + return lev._shallow_copy(vals) + return MultiIndex(levels=self.new_index_levels, + labels=result_labels, + names=self.new_index_names, + verify_integrity=False) def _unstack_multiple(data, clocs): if len(clocs) == 0: @@ -483,29 +443,10 @@ def _unstack_frame(obj, level): def get_compressed_ids(labels, sizes): - # no overflow - if com._long_prod(sizes) < 2 ** 63: - group_index = get_group_index(labels, sizes) - comp_index, obs_ids = _compress_group_index(group_index) - else: - n = len(labels[0]) - mask = np.zeros(n, dtype=bool) - for v in labels: - mask |= v < 0 - - while com._long_prod(sizes) >= 2 ** 63: - i = len(sizes) - while com._long_prod(sizes[:i]) >= 2 ** 63: - i -= 1 - - rem_index, rem_ids = get_compressed_ids(labels[:i], - sizes[:i]) - sizes = [len(rem_ids)] + sizes[i:] - labels = [rem_index] + labels[i:] - - return get_compressed_ids(labels, sizes) + from pandas.core.groupby import get_flat_ids - return comp_index, obs_ids + ids = get_flat_ids(labels, sizes, True) + return _compress_group_index(ids, sort=True) def stack(frame, level=-1, dropna=True): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index a19a32ea793ba..fcbfb21bd20e3 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -11,7 +11,7 @@ import nose import functools import itertools -from itertools import product +from itertools import product, permutations from distutils.version import LooseVersion from pandas.compat import( @@ -12334,6 +12334,53 @@ def test_unstack_non_unique_index_names(self): with tm.assertRaises(ValueError): df.T.stack('c1') + def test_unstack_nan_index(self): # GH7466 + cast = lambda val: '{0:1}'.format('' if val != val else val) + nan = np.nan + + def verify(df): + mk_list = lambda a: list(a) if isinstance(a, tuple) else [a] + rows, cols = df.notnull().values.nonzero() + for i, j in zip(rows, cols): + left = sorted(df.iloc[i, j].split('.')) + right = mk_list(df.index[i]) + mk_list(df.columns[j]) + right = sorted(list(map(cast, right))) + self.assertEqual(left, right) + + df = DataFrame({'jim':['a', 'b', nan, 'd'], + 'joe':['w', 'x', 'y', 'z'], + 'jolie':['a.w', 'b.x', ' .y', 'd.z']}) + + left = df.set_index(['jim', 'joe']).unstack()['jolie'] + right = df.set_index(['joe', 'jim']).unstack()['jolie'].T + assert_frame_equal(left, right) + + for idx in permutations(df.columns[:2]): + mi = df.set_index(list(idx)) + for lev in range(2): + udf = mi.unstack(level=lev) + self.assertEqual(udf.notnull().values.sum(), len(df)) + verify(udf['jolie']) + + df = DataFrame({'1st':['d'] * 3 + [nan] * 5 + ['a'] * 2 + + ['c'] * 3 + ['e'] * 2 + ['b'] * 5, + '2nd':['y'] * 2 + ['w'] * 3 + [nan] * 3 + + ['z'] * 4 + [nan] * 3 + ['x'] * 3 + [nan] * 2, + '3rd':[67,39,53,72,57,80,31,18,11,30,59, + 50,62,59,76,52,14,53,60,51]}) + + df['4th'], df['5th'] = \ + df.apply(lambda r: '.'.join(map(cast, r)), axis=1), \ + df.apply(lambda r: '.'.join(map(cast, r.iloc[::-1])), axis=1) + + for idx in permutations(['1st', '2nd', '3rd']): + mi = df.set_index(list(idx)) + for lev in range(3): + udf = mi.unstack(level=lev) + self.assertEqual(udf.notnull().values.sum(), 2 * len(df)) + for col in ['4th', '5th']: + verify(udf[col]) + def test_stack_datetime_column_multiIndex(self): # GH 8039 t = datetime(2014, 1, 1) diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index 23350b203ee50..39d189b7de52b 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -173,13 +173,16 @@ def test_pivot_multi_functions(self): def test_pivot_index_with_nan(self): # GH 3588 nan = np.nan - df = DataFrame({"a":['R1', 'R2', nan, 'R4'], 'b':["C1", "C2", "C3" , "C4"], "c":[10, 15, nan , 20]}) + df = DataFrame({'a':['R1', 'R2', nan, 'R4'], + 'b':['C1', 'C2', 'C3' , 'C4'], + 'c':[10, 15, 17, 20]}) result = df.pivot('a','b','c') - expected = DataFrame([[nan,nan,nan,nan],[nan,10,nan,nan], - [nan,nan,nan,nan],[nan,nan,15,20]], - index = Index(['R1','R2',nan,'R4'],name='a'), + expected = DataFrame([[nan,nan,17,nan],[10,nan,nan,nan], + [nan,15,nan,nan],[nan,nan,nan,20]], + index = Index([nan,'R1','R2','R4'],name='a'), columns = Index(['C1','C2','C3','C4'],name='b')) tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df.pivot('b', 'a', 'c'), expected.T) def test_pivot_with_tz(self): # GH 5878 @@ -268,12 +271,12 @@ def _check_output(res, col, index=['A', 'B'], columns=['C']): # issue number #8349: pivot_table with margins and dictionary aggfunc - df=DataFrame([ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17}, - {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110}, - {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80}, + df=DataFrame([ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17}, + {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110}, + {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80}, {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 2,'DAYS': 5,'SALARY':190} ]) df=df.set_index(['JOB','NAME','YEAR','MONTH'],drop=False,append=False)
closes https://github.com/pydata/pandas/issues/7466 on branch: ``` >>> df a b c 0 R1 C1 10 1 R2 C2 15 2 NaN C3 17 3 R4 C4 20 >>> df.pivot('a', 'b', 'c').fillna('.') b C1 C2 C3 C4 a NaN . . 17 . R1 10 . . . R2 . 15 . . R4 . . . 20 >>> df.pivot('b', 'a', 'c').fillna('.') a NaN R1 R2 R4 b C1 . 10 . . C2 . . 15 . C3 17 . . . C4 . . . 20 ``` the `pivot` function requires the `unstack` function to work with `nan`s in the index: ``` >>> df 4th 5th 1st 2nd 3rd d y 67 d.y.67 67.y.d 39 d.y.39 39.y.d w 53 d.w.53 53.w.d NaN w 72 .w.72 72.w. 57 .w.57 57.w. NaN 80 . .80 80. . 31 . .31 31. . 18 . .18 18. . a z 11 a.z.11 11.z.a 30 a.z.30 30.z.a c z 59 c.z.59 59.z.c 50 c.z.50 50.z.c NaN 62 c. .62 62. .c e NaN 59 e. .59 59. .e 76 e. .76 76. .e b x 52 b.x.52 52.x.b 14 b.x.14 14.x.b 53 b.x.53 53.x.b NaN 60 b. .60 60. .b 51 b. .51 51. .b ``` the `4th` and `5th` column are so that it is easy to verify the frame: ``` >>> df.unstack(level=1).fillna('-') 4th 5th 2nd NaN w x y z NaN w x y z 1st 3rd NaN 18 . .18 - - - - 18. . - - - - 31 . .31 - - - - 31. . - - - - 57 - .w.57 - - - - 57.w. - - - 72 - .w.72 - - - - 72.w. - - - 80 . .80 - - - - 80. . - - - - a 11 - - - - a.z.11 - - - - 11.z.a 30 - - - - a.z.30 - - - - 30.z.a b 14 - - b.x.14 - - - - 14.x.b - - 51 b. .51 - - - - 51. .b - - - - 52 - - b.x.52 - - - - 52.x.b - - 53 - - b.x.53 - - - - 53.x.b - - 60 b. .60 - - - - 60. .b - - - - c 50 - - - - c.z.50 - - - - 50.z.c 59 - - - - c.z.59 - - - - 59.z.c 62 c. .62 - - - - 62. .c - - - - d 39 - - - d.y.39 - - - - 39.y.d - 53 - d.w.53 - - - - 53.w.d - - - 67 - - - d.y.67 - - - - 67.y.d - e 59 e. .59 - - - - 59. .e - - - - 76 e. .76 - - - - 76. .e - - - - ``` `nan` values are kept out of levels and are handled by labels: ``` >>> df.unstack(level=1).index MultiIndex(levels=[['a', 'b', 'c', 'd', 'e'], [11, 14, 18, 30, 31, 39, 50, 51, 52, 53, 57, 59, 60, 62, 67, 72, 76, 80]], labels=[[-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4], [2, 4, 10, 15, 17, 0, 3, 1, 7, 8, 9, 12, 6, 11, 13, 5, 9, 14, 11, 16]], names=['1st', '3rd']) >>> df.unstack(level=1).columns MultiIndex(levels=[['4th', '5th'], ['w', 'x', 'y', 'z']], labels=[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [-1, 0, 1, 2, 3, -1, 0, 1, 2, 3]], names=[None, '2nd']) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/9061
2014-12-12T02:10:36Z
2014-12-22T13:08:53Z
2014-12-22T13:08:52Z
2015-01-10T20:21:07Z
DOC: fix-up docs for 0.15.2 release
diff --git a/doc/source/io.rst b/doc/source/io.rst index 2ec61f7f00bd8..d5bbddfeb7d37 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3403,7 +3403,7 @@ writes ``data`` to the database in batches of 1000 rows at a time: data.to_sql('data_chunked', engine, chunksize=1000) SQL data types -"""""""""""""" +++++++++++++++ :func:`~pandas.DataFrame.to_sql` will try to map your data to an appropriate SQL data type based on the dtype of the data. When you have columns of dtype @@ -3801,7 +3801,7 @@ is lost when exporting. Labeled data can similarly be imported from *Stata* data files as ``Categorical`` variables using the keyword argument ``convert_categoricals`` (``True`` by default). The keyword argument ``order_categoricals`` (``True`` by default) determines - whether imported ``Categorical`` variables are ordered. +whether imported ``Categorical`` variables are ordered. .. note:: diff --git a/doc/source/release.rst b/doc/source/release.rst index 321947111574b..6d952344576e6 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -50,7 +50,9 @@ pandas 0.15.2 **Release date:** (December 12, 2014) -This is a minor release from 0.15.1 and includes a small number of API changes, several new features, enhancements, and performance improvements along with a large number of bug fixes. +This is a minor release from 0.15.1 and includes a large number of bug fixes +along with several new features, enhancements, and performance improvements. +A small number of API changes were necessary to fix existing bugs. See the :ref:`v0.15.2 Whatsnew <whatsnew_0152>` overview for an extensive list of all API changes, enhancements and bugs that have been fixed in 0.15.2. diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3a0fdbae5e297..02de919e3f83e 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -3,9 +3,10 @@ v0.15.2 (December 12, 2014) --------------------------- -This is a minor release from 0.15.1 and includes a small number of API changes, several new features, -enhancements, and performance improvements along with a large number of bug fixes. We recommend that all -users upgrade to this version. +This is a minor release from 0.15.1 and includes a large number of bug fixes +along with several new features, enhancements, and performance improvements. +A small number of API changes were necessary to fix existing bugs. +We recommend that all users upgrade to this version. - :ref:`Enhancements <whatsnew_0152.enhancements>` - :ref:`API Changes <whatsnew_0152.api>` @@ -16,6 +17,7 @@ users upgrade to this version. API changes ~~~~~~~~~~~ + - Indexing in ``MultiIndex`` beyond lex-sort depth is now supported, though a lexically sorted index will have a better performance. (:issue:`2646`) @@ -38,24 +40,30 @@ API changes df2.index.lexsort_depth df2.loc[(1,'z')] -- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) - - Bug in unique of Series with ``category`` dtype, which returned all categories regardless whether they were "used" or not (see :issue:`8559` for the discussion). + Previous behaviour was to return all categories: -- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`): + .. code-block:: python - .. ipython:: python + In [3]: cat = pd.Categorical(['a', 'b', 'a'], categories=['a', 'b', 'c']) - s = pd.Series([False, True, False], index=[0, 0, 1]) - s.any(level=0) + In [4]: cat + Out[4]: + [a, b, a] + Categories (3, object): [a < b < c] -- ``Panel`` now supports the ``all`` and ``any`` aggregation functions. (:issue:`8302`): + In [5]: cat.unique() + Out[5]: array(['a', 'b', 'c'], dtype=object) + + Now, only the categories that do effectively occur in the array are returned: .. ipython:: python - p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) - p.all() + cat = pd.Categorical(['a', 'b', 'a'], categories=['a', 'b', 'c']) + cat.unique() + +- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`). - Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) @@ -90,25 +98,70 @@ API changes - ``Timestamp('now')`` is now equivalent to ``Timestamp.now()`` in that it returns the local time rather than UTC. Also, ``Timestamp('today')`` is now equivalent to ``Timestamp.today()`` and both have ``tz`` as a possible argument. (:issue:`9000`) +- Fix negative step support for label-based slices (:issue:`8753`) + + Old behavior: + + .. code-block:: python + + In [1]: s = pd.Series(np.arange(3), ['a', 'b', 'c']) + Out[1]: + a 0 + b 1 + c 2 + dtype: int64 + + In [2]: s.loc['c':'a':-1] + Out[2]: + c 2 + dtype: int64 + + New behavior: + + .. ipython:: python + + s = pd.Series(np.arange(3), ['a', 'b', 'c']) + s.loc['c':'a':-1] + + .. _whatsnew_0152.enhancements: Enhancements ~~~~~~~~~~~~ +``Categorical`` enhancements: + +- Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. +- Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. +- Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. +- Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). + +Other enhancements: + - Added the ability to specify the SQL type of columns when writing a DataFrame to a database (:issue:`8778`). For example, specifying to use the sqlalchemy ``String`` type instead of the default ``Text`` type for string columns: - .. code-block:: + .. code-block:: python from sqlalchemy.types import String data.to_sql('data_dtype', engine, dtype={'Col_1': String}) -- Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. -- Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. -- Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. -- Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). +- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters (:issue:`8302`): + + .. ipython:: python + + s = pd.Series([False, True, False], index=[0, 0, 1]) + s.any(level=0) + +- ``Panel`` now supports the ``all`` and ``any`` aggregation functions. (:issue:`8302`): + + .. ipython:: python + + p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) + p.all() + - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`). @@ -122,19 +175,22 @@ Enhancements - Added ability to read table footers to read_html (:issue:`8552`) - ``to_sql`` now infers datatypes of non-NA values for columns that contain NA values and have dtype ``object`` (:issue:`8778`). + .. _whatsnew_0152.performance: Performance ~~~~~~~~~~~ -- Reduce memory usage when skiprows is an integer in read_csv (:issue:`8681`) +- Reduce memory usage when skiprows is an integer in read_csv (:issue:`8681`) - Performance boost for ``to_datetime`` conversions with a passed ``format=``, and the ``exact=False`` (:issue:`8904`) + .. _whatsnew_0152.bug_fixes: Bug Fixes ~~~~~~~~~ +- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) - Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) - Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) - Bug in using a ``pd.Grouper(key=...)`` with no level/axis or level only (:issue:`8795`, :issue:`8866`) @@ -154,95 +210,32 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) - Bug in certain operations with dateutil timezones, manifesting with dateutil 2.3 (:issue:`8639`) - -- Fix negative step support for label-based slices (:issue:`8753`) - - Old behavior: - - .. code-block:: python - - In [1]: s = pd.Series(np.arange(3), ['a', 'b', 'c']) - Out[1]: - a 0 - b 1 - c 2 - dtype: int64 - - In [2]: s.loc['c':'a':-1] - Out[2]: - c 2 - dtype: int64 - - New behavior: - - .. ipython:: python - - s = pd.Series(np.arange(3), ['a', 'b', 'c']) - s.loc['c':'a':-1] - - Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (:issue:`8890`) - Bug in ``to_datetime`` when parsing a nanoseconds using the ``%f`` format (:issue:`8989`) - ``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`). - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) - Bug in outputing a Multindex with ``to_html,index=False`` which would add an extra column (:issue:`8452`) - - - - - - - - Imported categorical variables from Stata files retain the ordinal information in the underlying data (:issue:`8836`). - - - - Defined ``.size`` attribute across ``NDFrame`` objects to provide compat with numpy >= 1.9.1; buggy with ``np.array_split`` (:issue:`8846`) - - - Skip testing of histogram plots for matplotlib <= 1.2 (:issue:`8648`). - - - - - - - Bug where ``get_data_google`` returned object dtypes (:issue:`3995`) - - Bug in ``DataFrame.stack(..., dropna=False)`` when the DataFrame's ``columns`` is a ``MultiIndex`` whose ``labels`` do not reference all its ``levels``. (:issue:`8844`) - - - Bug in that Option context applied on ``__enter__`` (:issue:`8514`) - - - Bug in resample that causes a ValueError when resampling across multiple days and the last offset is not calculated from the start of the range (:issue:`8683`) - - - - Bug where ``DataFrame.plot(kind='scatter')`` fails when checking if an np.array is in the DataFrame (:issue:`8852`) - - - - Bug in ``pd.infer_freq/DataFrame.inferred_freq`` that prevented proper sub-daily frequency inference when the index contained DST days (:issue:`8772`). - Bug where index name was still used when plotting a series with ``use_index=False`` (:issue:`8558`). - Bugs when trying to stack multiple columns, when some (or all) of the level names are numbers (:issue:`8584`). - Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`), (:issue:`8983`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) - - - - - - - Bug in `StataWriter` the produces writes strings with 244 characters irrespective of actual size (:issue:`8969`) - - - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) - Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) - Bug in plotting if sharex was enabled and index was a timeseries, would show labels on multiple axes (:issue:`3964`). - - Bug where passing a unit to the TimedeltaIndex constructor applied the to nano-second conversion twice. (:issue:`9011`). - Bug in plotting of a period-like array (:issue:`9012`) +
@jreback some more clean-up of whatsnew - some small fixes so now everything builds ok, ready for release I also reworded a little bit the intro of the minor release (I thought was a bit more appropriate for minor release vs major release)
https://api.github.com/repos/pandas-dev/pandas/pulls/9058
2014-12-11T13:32:05Z
2014-12-11T13:41:59Z
2014-12-11T13:41:59Z
2014-12-11T13:41:59Z
TST: start tests for PeriodConverter
diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py index 03a3d450827b9..a9fee1d5c3ee6 100644 --- a/pandas/tseries/converter.py +++ b/pandas/tseries/converter.py @@ -109,7 +109,7 @@ class PeriodConverter(dates.DateConverter): def convert(values, units, axis): if not hasattr(axis, 'freq'): raise TypeError('Axis must have `freq` set to convert to Periods') - valid_types = (str, datetime, Period, pydt.date, pydt.time) + valid_types = (compat.string_types, datetime, Period, pydt.date, pydt.time) if (isinstance(values, valid_types) or com.is_integer(values) or com.is_float(values)): return get_datevalue(values, axis.freq) @@ -127,7 +127,7 @@ def convert(values, units, axis): def get_datevalue(date, freq): if isinstance(date, Period): return date.asfreq(freq).ordinal - elif isinstance(date, (str, datetime, pydt.date, pydt.time)): + elif isinstance(date, (compat.string_types, datetime, pydt.date, pydt.time)): return Period(date, freq).ordinal elif (com.is_integer(date) or com.is_float(date) or (isinstance(date, (np.ndarray, Index)) and (date.size == 1))): diff --git a/pandas/tseries/tests/test_converter.py b/pandas/tseries/tests/test_converter.py index b5a284d5f50ea..95c0b4466da26 100644 --- a/pandas/tseries/tests/test_converter.py +++ b/pandas/tseries/tests/test_converter.py @@ -6,7 +6,7 @@ import numpy as np from numpy.testing import assert_almost_equal as np_assert_almost_equal -from pandas import Timestamp +from pandas import Timestamp, Period from pandas.compat import u import pandas.util.testing as tm from pandas.tseries.offsets import Second, Milli, Micro @@ -103,6 +103,60 @@ def _assert_less(ts1, ts2): _assert_less(ts, ts + Micro(50)) +class TestPeriodConverter(tm.TestCase): + + def setUp(self): + self.pc = converter.PeriodConverter() + + class Axis(object): + pass + + self.axis = Axis() + self.axis.freq = 'D' + + def test_convert_accepts_unicode(self): + r1 = self.pc.convert("2012-1-1", None, self.axis) + r2 = self.pc.convert(u("2012-1-1"), None, self.axis) + self.assert_equal(r1, r2, "PeriodConverter.convert should accept unicode") + + def test_conversion(self): + rs = self.pc.convert(['2012-1-1'], None, self.axis)[0] + xp = Period('2012-1-1').ordinal + self.assertEqual(rs, xp) + + rs = self.pc.convert('2012-1-1', None, self.axis) + self.assertEqual(rs, xp) + + rs = self.pc.convert([date(2012, 1, 1)], None, self.axis)[0] + self.assertEqual(rs, xp) + + rs = self.pc.convert(date(2012, 1, 1), None, self.axis) + self.assertEqual(rs, xp) + + rs = self.pc.convert([Timestamp('2012-1-1')], None, self.axis)[0] + self.assertEqual(rs, xp) + + rs = self.pc.convert(Timestamp('2012-1-1'), None, self.axis) + self.assertEqual(rs, xp) + + # FIXME + # rs = self.pc.convert(np.datetime64('2012-01-01'), None, self.axis) + # self.assertEqual(rs, xp) + # + # rs = self.pc.convert(np.datetime64('2012-01-01 00:00:00+00:00'), None, self.axis) + # self.assertEqual(rs, xp) + # + # rs = self.pc.convert(np.array([np.datetime64('2012-01-01 00:00:00+00:00'), + # np.datetime64('2012-01-02 00:00:00+00:00')]), None, self.axis) + # self.assertEqual(rs[0], xp) + + def test_integer_passthrough(self): + # GH9012 + rs = self.pc.convert([0, 1], None, self.axis) + xp = [0, 1] + self.assertEqual(rs, xp) + + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
@jreback The tests I started related to PR #9050
https://api.github.com/repos/pandas-dev/pandas/pulls/9055
2014-12-11T10:29:35Z
2014-12-12T15:25:07Z
2014-12-12T15:25:07Z
2014-12-12T15:25:07Z
TST: dateutil fixes (GH8639)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index f034e0e223e6b..6936e40da6fbe 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -163,6 +163,7 @@ Bug Fixes - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) +- Bug in certain operations with dateutil timezones, manifesting with dateutil 2.3 (:issue:`8639`) - Fix negative step support for label-based slices (:issue:`8753`) diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index 500e19d36fff6..d568a75f6874d 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -371,31 +371,31 @@ def test_range_tz_pytz(self): self.assertEqual(dr.tz.zone, tz.zone) self.assertEqual(dr[0], start) self.assertEqual(dr[2], end) - + def test_range_tz_dst_straddle_pytz(self): - + tm._skip_if_no_pytz() from pytz import timezone tz = timezone('US/Eastern') - dates = [(tz.localize(datetime(2014, 3, 6)), + dates = [(tz.localize(datetime(2014, 3, 6)), tz.localize(datetime(2014, 3, 12))), - (tz.localize(datetime(2013, 11, 1)), + (tz.localize(datetime(2013, 11, 1)), tz.localize(datetime(2013, 11, 6)))] for (start, end) in dates: dr = date_range(start, end, freq='D') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) self.assertEqual(np.all(dr.hour==0), True) - + dr = date_range(start, end, freq='D', tz='US/Eastern') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) - self.assertEqual(np.all(dr.hour==0), True) - + self.assertEqual(np.all(dr.hour==0), True) + dr = date_range(start.replace(tzinfo=None), end.replace(tzinfo=None), freq='D', tz='US/Eastern') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) - self.assertEqual(np.all(dr.hour==0), True) + self.assertEqual(np.all(dr.hour==0), True) def test_range_tz_dateutil(self): # GH 2906 @@ -441,7 +441,7 @@ def test_month_range_union_tz_pytz(self): def test_month_range_union_tz_dateutil(self): _skip_if_windows_python_3() tm._skip_if_no_dateutil() - from dateutil.tz import gettz as timezone + from dateutil.zoneinfo import gettz as timezone tz = timezone('US/Eastern') early_start = datetime(2011, 1, 1) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 7a428fd629125..9b8200e266e5a 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -419,7 +419,7 @@ def test_timestamp_to_datetime_explicit_dateutil(self): tm._skip_if_no_dateutil() import dateutil rng = date_range('20090415', '20090519', - tz=dateutil.tz.gettz('US/Eastern')) + tz=dateutil.zoneinfo.gettz('US/Eastern')) stamp = rng[0] dtval = stamp.to_pydatetime() @@ -1797,7 +1797,7 @@ def test_append_concat_tz_explicit_pytz(self): def test_append_concat_tz_dateutil(self): # GH 2938 tm._skip_if_no_dateutil() - from dateutil.tz import gettz as timezone + from dateutil.zoneinfo import gettz as timezone rng = date_range('5/8/2012 1:45', periods=10, freq='5T', tz='dateutil/US/Eastern') diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py index 9fbdb714d8cfa..752d12743a5d3 100644 --- a/pandas/tseries/tests/test_timezones.py +++ b/pandas/tseries/tests/test_timezones.py @@ -443,7 +443,7 @@ def test_ambiguous_infer(self): localized_old = di.tz_localize(tz, infer_dst=True) self.assert_numpy_array_equal(dr, localized_old) self.assert_numpy_array_equal(dr, DatetimeIndex(times, tz=tz, ambiguous='infer')) - + # When there is no dst transition, nothing special happens dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=datetools.Hour()) @@ -463,31 +463,31 @@ def test_ambiguous_flags(self): times = ['11/06/2011 00:00', '11/06/2011 01:00', '11/06/2011 01:00', '11/06/2011 02:00', '11/06/2011 03:00'] - + # Test tz_localize di = DatetimeIndex(times) is_dst = [1, 1, 0, 0, 0] localized = di.tz_localize(tz, ambiguous=is_dst) self.assert_numpy_array_equal(dr, localized) self.assert_numpy_array_equal(dr, DatetimeIndex(times, tz=tz, ambiguous=is_dst)) - + localized = di.tz_localize(tz, ambiguous=np.array(is_dst)) self.assert_numpy_array_equal(dr, localized) - + localized = di.tz_localize(tz, ambiguous=np.array(is_dst).astype('bool')) self.assert_numpy_array_equal(dr, localized) - + # Test constructor localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst) self.assert_numpy_array_equal(dr, localized) - + # Test duplicate times where infer_dst fails times += times di = DatetimeIndex(times) - + # When the sizes are incompatible, make sure error is raised self.assertRaises(Exception, di.tz_localize, tz, ambiguous=is_dst) - + # When sizes are compatible and there are repeats ('infer' won't work) is_dst = np.hstack((is_dst, is_dst)) localized = di.tz_localize(tz, ambiguous=is_dst) @@ -501,7 +501,7 @@ def test_ambiguous_flags(self): localized = dr.tz_localize(tz) localized_is_dst = dr.tz_localize(tz, ambiguous=is_dst) self.assert_numpy_array_equal(localized, localized_is_dst) - + def test_ambiguous_nat(self): tz = self.tz('US/Eastern') times = ['11/06/2011 00:00', '11/06/2011 01:00', @@ -509,7 +509,7 @@ def test_ambiguous_nat(self): '11/06/2011 03:00'] di = DatetimeIndex(times) localized = di.tz_localize(tz, ambiguous='NaT') - + times = ['11/06/2011 00:00', np.NaN, np.NaN, '11/06/2011 02:00', '11/06/2011 03:00'] diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index ad0ef67b5aca2..679fd2992855c 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -1,5 +1,5 @@ import nose - +from distutils.version import LooseVersion import numpy as np from pandas import tslib @@ -137,13 +137,24 @@ def test_constructor_with_stringoffset(self): self.assertEqual(result, eval(repr(result))) def test_repr(self): + tm._skip_if_no_pytz() + tm._skip_if_no_dateutil() + dates = ['2014-03-07', '2014-01-01 09:00', '2014-01-01 00:00:00.000000001'] - timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles'] + + # dateutil zone change (only matters for repr) + import dateutil + if dateutil.__version__ >= LooseVersion('2.3'): + timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific'] + else: + timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles'] + freqs = ['D', 'M', 'S', 'N'] for date in dates: for tz in timezones: for freq in freqs: + # avoid to match with timezone name freq_repr = "'{0}'".format(freq) if tz.startswith('dateutil'): @@ -306,10 +317,10 @@ def test_now(self): ts_from_string = Timestamp('now') ts_from_method = Timestamp.now() ts_datetime = datetime.datetime.now() - + ts_from_string_tz = Timestamp('now', tz='US/Eastern') ts_from_method_tz = Timestamp.now(tz='US/Eastern') - + # Check that the delta between the times is less than 1s (arbitrarily small) delta = Timedelta(seconds=1) self.assertTrue((ts_from_method - ts_from_string) < delta) @@ -321,10 +332,10 @@ def test_today(self): ts_from_string = Timestamp('today') ts_from_method = Timestamp.today() ts_datetime = datetime.datetime.today() - + ts_from_string_tz = Timestamp('today', tz='US/Eastern') ts_from_method_tz = Timestamp.today(tz='US/Eastern') - + # Check that the delta between the times is less than 1s (arbitrarily small) delta = Timedelta(seconds=1) self.assertTrue((ts_from_method - ts_from_string) < delta) @@ -737,7 +748,7 @@ def test_resolution(self): for freq, expected in zip(['A', 'Q', 'M', 'D', 'H', 'T', 'S', 'L', 'U'], [tslib.D_RESO, tslib.D_RESO, tslib.D_RESO, tslib.D_RESO, tslib.H_RESO, tslib.T_RESO,tslib.S_RESO, tslib.MS_RESO, tslib.US_RESO]): - for tz in [None, 'Asia/Tokyo', 'US/Eastern']: + for tz in [None, 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Eastern']: idx = date_range(start='2013-04-01', periods=30, freq=freq, tz=tz) result = tslib.resolution(idx.asi8, idx.tz) self.assertEqual(result, expected) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 1976eee96296c..e3e18b912132d 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -133,8 +133,8 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, offset=None, box=False): dt = dt + tz.utcoffset(dt) result[i] = dt else: - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + for i in range(n): value = arr[i] @@ -223,10 +223,10 @@ class Timestamp(_Timestamp): @classmethod def now(cls, tz=None): - """ + """ Return the current time in the local timezone. Equivalent to datetime.now([tz]) - + Parameters ---------- tz : string / timezone object, default None @@ -242,7 +242,7 @@ class Timestamp(_Timestamp): Return the current time in the local timezone. This differs from datetime.today() in that it can be localized to a passed timezone. - + Parameters ---------- tz : string / timezone object, default None @@ -1045,12 +1045,12 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if util.is_string_object(ts): if ts in _nat_strings: ts = NaT - elif ts == 'now': - # Issue 9000, we short-circuit rather than going + elif ts == 'now': + # Issue 9000, we short-circuit rather than going # into np_datetime_strings which returns utc ts = Timestamp.now(tz) - elif ts == 'today': - # Issue 9000, we short-circuit rather than going + elif ts == 'today': + # Issue 9000, we short-circuit rather than going # into np_datetime_strings which returns a normalized datetime ts = Timestamp.today(tz) else: @@ -1174,8 +1174,8 @@ cdef inline void _localize_tso(_TSObject obj, object tz): obj.tzinfo = tz else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + pos = trans.searchsorted(obj.value, side='right') - 1 @@ -2566,8 +2566,8 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): * 1000000000) utc_dates[i] = v - delta else: - deltas = _get_deltas(tz1) - trans = _get_transitions(tz1) + trans, deltas, typ = _get_dst_info(tz1) + trans_len = len(trans) pos = trans.searchsorted(vals[0]) - 1 if pos < 0: @@ -2598,9 +2598,9 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): return result # Convert UTC to other timezone - trans = _get_transitions(tz2) + trans, deltas, typ = _get_dst_info(tz2) trans_len = len(trans) - deltas = _get_deltas(tz2) + pos = trans.searchsorted(utc_dates[0]) - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2639,8 +2639,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2): delta = int(total_seconds(_get_utcoffset(tz1, dt))) * 1000000000 utc_date = val - delta elif _get_zone(tz1) != 'UTC': - deltas = _get_deltas(tz1) - trans = _get_transitions(tz1) + trans, deltas, typ = _get_dst_info(tz1) pos = trans.searchsorted(val, side='right') - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2658,8 +2657,8 @@ def tz_convert_single(int64_t val, object tz1, object tz2): delta = int(total_seconds(_get_utcoffset(tz2, dt))) * 1000000000 return utc_date + delta # Convert UTC to other timezone - trans = _get_transitions(tz2) - deltas = _get_deltas(tz2) + trans, deltas, typ = _get_dst_info(tz2) + pos = trans.searchsorted(utc_date, side='right') - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2668,8 +2667,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2): return utc_date + offset # Timezone data caches, key is the pytz string or dateutil file name. -trans_cache = {} -utc_offset_cache = {} +dst_cache = {} cdef inline bint _treat_tz_as_pytz(object tz): return hasattr(tz, '_utc_transition_times') and hasattr(tz, '_transition_info') @@ -2708,40 +2706,67 @@ cdef inline object _tz_cache_key(object tz): return None -cdef object _get_transitions(object tz): +cdef object _get_dst_info(object tz): """ - Get UTC times of DST transitions + return a tuple of : + (UTC times of DST transitions, + UTC offsets in microseconds corresponding to DST transitions, + string of type of transitions) + """ cache_key = _tz_cache_key(tz) if cache_key is None: - return np.array([NPY_NAT + 1], dtype=np.int64) + num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 + return (np.array([NPY_NAT + 1], dtype=np.int64), + np.array([num], dtype=np.int64), + None) - if cache_key not in trans_cache: + if cache_key not in dst_cache: if _treat_tz_as_pytz(tz): - arr = np.array(tz._utc_transition_times, dtype='M8[ns]') - arr = arr.view('i8') + trans = np.array(tz._utc_transition_times, dtype='M8[ns]') + trans = trans.view('i8') try: if tz._utc_transition_times[0].year == 1: - arr[0] = NPY_NAT + 1 + trans[0] = NPY_NAT + 1 except Exception: pass + deltas = _unbox_utcoffsets(tz._transition_info) + typ = 'pytz' + elif _treat_tz_as_dateutil(tz): if len(tz._trans_list): # get utc trans times trans_list = _get_utc_trans_times_from_dateutil_tz(tz) - arr = np.hstack([np.array([0], dtype='M8[s]'), # place holder for first item - np.array(trans_list, dtype='M8[s]')]).astype('M8[ns]') # all trans listed - arr = arr.view('i8') - arr[0] = NPY_NAT + 1 + trans = np.hstack([np.array([0], dtype='M8[s]'), # place holder for first item + np.array(trans_list, dtype='M8[s]')]).astype('M8[ns]') # all trans listed + trans = trans.view('i8') + trans[0] = NPY_NAT + 1 + + # deltas + deltas = np.array([v.offset for v in (tz._ttinfo_before,) + tz._trans_idx], dtype='i8') # + (tz._ttinfo_std,) + deltas *= 1000000000 + typ = 'dateutil' + elif _is_fixed_offset(tz): - arr = np.array([NPY_NAT + 1], dtype=np.int64) + trans = np.array([NPY_NAT + 1], dtype=np.int64) + deltas = np.array([tz._ttinfo_std.offset], dtype='i8') * 1000000000 + typ = 'fixed' else: - arr = np.array([], dtype='M8[ns]') + trans = np.array([], dtype='M8[ns]') + deltas = np.array([], dtype='i8') + typ = None + + else: - arr = np.array([NPY_NAT + 1], dtype=np.int64) - trans_cache[cache_key] = arr - return trans_cache[cache_key] + # static tzinfo + trans = np.array([NPY_NAT + 1], dtype=np.int64) + num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 + deltas = np.array([num], dtype=np.int64) + typ = 'static' + + dst_cache[cache_key] = (trans, deltas, typ) + return dst_cache[cache_key] cdef object _get_utc_trans_times_from_dateutil_tz(object tz): ''' @@ -2756,35 +2781,6 @@ cdef object _get_utc_trans_times_from_dateutil_tz(object tz): new_trans[i] = trans - last_std_offset return new_trans - -cdef object _get_deltas(object tz): - """ - Get UTC offsets in microseconds corresponding to DST transitions - """ - cache_key = _tz_cache_key(tz) - if cache_key is None: - num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 - return np.array([num], dtype=np.int64) - - if cache_key not in utc_offset_cache: - if _treat_tz_as_pytz(tz): - utc_offset_cache[cache_key] = _unbox_utcoffsets(tz._transition_info) - elif _treat_tz_as_dateutil(tz): - if len(tz._trans_list): - arr = np.array([v.offset for v in (tz._ttinfo_before,) + tz._trans_idx], dtype='i8') # + (tz._ttinfo_std,) - arr *= 1000000000 - utc_offset_cache[cache_key] = arr - elif _is_fixed_offset(tz): - utc_offset_cache[cache_key] = np.array([tz._ttinfo_std.offset], dtype='i8') * 1000000000 - else: - utc_offset_cache[cache_key] = np.array([], dtype='i8') - else: - # static tzinfo - num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 - utc_offset_cache[cache_key] = np.array([num], dtype=np.int64) - - return utc_offset_cache[cache_key] - def tot_seconds(td): return total_seconds(td) @@ -2852,8 +2848,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None): if len(ambiguous) != len(vals): raise ValueError("Length of ambiguous bool-array must be the same size as vals") - trans = _get_transitions(tz) # transition dates - deltas = _get_deltas(tz) # utc offsets + trans, deltas, typ = _get_dst_info(tz) tdata = <int64_t*> trans.data ntrans = len(trans) @@ -3464,15 +3459,15 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz): result[i] = _normalized_stamp(&dts) else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT @@ -3521,8 +3516,8 @@ def dates_normalized(ndarray[int64_t] stamps, tz=None): if dt.hour > 0: return False else: - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + for i in range(n): # Adjust datetime64 timestamp, recompute datetimestruct pos = trans.searchsorted(stamps[i]) - 1 @@ -3609,15 +3604,15 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, dts.hour, dts.min, dts.sec, dts.us, dts.ps, freq) else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT @@ -4111,15 +4106,15 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz): reso = curr_reso else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: continue
xref #8639
https://api.github.com/repos/pandas-dev/pandas/pulls/9047
2014-12-09T01:21:31Z
2014-12-10T11:11:03Z
2014-12-10T11:11:03Z
2014-12-10T11:11:03Z
Fix timedelta json on windows
diff --git a/pandas/src/datetime_helper.h b/pandas/src/datetime_helper.h index 8e188a431a086..c8c54dd5fc947 100644 --- a/pandas/src/datetime_helper.h +++ b/pandas/src/datetime_helper.h @@ -1,4 +1,7 @@ #include "datetime.h" +#include "numpy/arrayobject.h" +#include "numpy/arrayscalars.h" +#include <stdio.h> #if PY_MAJOR_VERSION >= 3 #define PyInt_AS_LONG PyLong_AsLong @@ -9,15 +12,16 @@ void mangle_nat(PyObject *val) { PyDateTime_GET_DAY(val) = -1; } -long get_long_attr(PyObject *o, const char *attr) { - return PyInt_AS_LONG(PyObject_GetAttrString(o, attr)); +npy_int64 get_long_attr(PyObject *o, const char *attr) { + PyObject *value = PyObject_GetAttrString(o, attr); + return PyLong_Check(value) ? PyLong_AsLongLong(value) : PyInt_AS_LONG(value); } -double total_seconds(PyObject *td) { +npy_float64 total_seconds(PyObject *td) { // Python 2.6 compat - long microseconds = get_long_attr(td, "microseconds"); - long seconds = get_long_attr(td, "seconds"); - long days = get_long_attr(td, "days"); - long days_in_seconds = days * 24 * 3600; + npy_int64 microseconds = get_long_attr(td, "microseconds"); + npy_int64 seconds = get_long_attr(td, "seconds"); + npy_int64 days = get_long_attr(td, "days"); + npy_int64 days_in_seconds = days * 24LL * 3600LL; return (microseconds + (seconds + days_in_seconds) * 1000000.0) / 1000000.0; } diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index 00ba8975d58c8..25fbb71482f9e 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -1452,12 +1452,12 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) else if (PyDelta_Check(obj)) { - long value; + npy_int64 value; - if (PyObject_HasAttrString(obj, "value")) + if (PyObject_HasAttrString(obj, "value")) { value = get_long_attr(obj, "value"); - else - value = total_seconds(obj) * 1000000000; // nanoseconds per second + } else + value = total_seconds(obj) * 1000000000LL; // nanoseconds per second exc = PyErr_Occurred();
some fixes for different int sizes on windows
https://api.github.com/repos/pandas-dev/pandas/pulls/9044
2014-12-08T15:29:40Z
2014-12-08T16:32:56Z
2014-12-08T16:32:56Z
2014-12-09T00:51:22Z
ENH: Store in SQL using double precision
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index b3ac58a9fb84a..999f0cd0be8e7 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -202,3 +202,4 @@ Bug Fixes - Fixed issue in the ``xlsxwriter`` engine where it added a default 'General' format to cells if no other format wass applied. This prevented other row or column formatting being applied. (:issue:`9167`) - Fixes issue with ``index_col=False`` when ``usecols`` is also specified in ``read_csv``. (:issue:`9082`) - Bug where ``wide_to_long`` would modify the input stubnames list (:issue:`9204`) +- Bug in to_sql not storing float64 values using double precision. (:issue:`9009`) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index b4318bdc2a3bf..cd1c40b7b075a 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -908,7 +908,7 @@ def _sqlalchemy_type(self, col): col_type = self._get_notnull_col_dtype(col) - from sqlalchemy.types import (BigInteger, Float, Text, Boolean, + from sqlalchemy.types import (BigInteger, Integer, Float, Text, Boolean, DateTime, Date, Time) if col_type == 'datetime64' or col_type == 'datetime': @@ -923,10 +923,15 @@ def _sqlalchemy_type(self, col): "database.", UserWarning) return BigInteger elif col_type == 'floating': - return Float + if col.dtype == 'float32': + return Float(precision=23) + else: + return Float(precision=53) elif col_type == 'integer': - # TODO: Refine integer size. - return BigInteger + if col.dtype == 'int32': + return Integer + else: + return BigInteger elif col_type == 'boolean': return Boolean elif col_type == 'date': @@ -1187,9 +1192,17 @@ def has_table(self, name, schema=None): def get_table(self, table_name, schema=None): schema = schema or self.meta.schema if schema: - return self.meta.tables.get('.'.join([schema, table_name])) + tbl = self.meta.tables.get('.'.join([schema, table_name])) else: - return self.meta.tables.get(table_name) + tbl = self.meta.tables.get(table_name) + + # Avoid casting double-precision floats into decimals + from sqlalchemy import Numeric + for column in tbl.columns: + if isinstance(column.type, Numeric): + column.type.asdecimal = False + + return tbl def drop_table(self, table_name, schema=None): schema = schema or self.meta.schema @@ -1198,8 +1211,9 @@ def drop_table(self, table_name, schema=None): self.get_table(table_name, schema).drop() self.meta.clear() - def _create_sql_schema(self, frame, table_name, keys=None): - table = SQLTable(table_name, self, frame=frame, index=False, keys=keys) + def _create_sql_schema(self, frame, table_name, keys=None, dtype=None): + table = SQLTable(table_name, self, frame=frame, index=False, keys=keys, + dtype=dtype) return str(table.sql_schema()) @@ -1213,7 +1227,7 @@ def _create_sql_schema(self, frame, table_name, keys=None): 'sqlite': 'TEXT', }, 'floating': { - 'mysql': 'FLOAT', + 'mysql': 'DOUBLE', 'sqlite': 'REAL', }, 'integer': { @@ -1520,13 +1534,13 @@ def drop_table(self, name, schema=None): drop_sql = "DROP TABLE %s" % name self.execute(drop_sql) - def _create_sql_schema(self, frame, table_name, keys=None): + def _create_sql_schema(self, frame, table_name, keys=None, dtype=None): table = SQLiteTable(table_name, self, frame=frame, index=False, - keys=keys) + keys=keys, dtype=dtype) return str(table.sql_schema()) -def get_schema(frame, name, flavor='sqlite', keys=None, con=None): +def get_schema(frame, name, flavor='sqlite', keys=None, con=None, dtype=None): """ Get the SQL db table schema for the given frame. @@ -1545,11 +1559,14 @@ def get_schema(frame, name, flavor='sqlite', keys=None, con=None): Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ pandas_sql = pandasSQL_builder(con=con, flavor=flavor) - return pandas_sql._create_sql_schema(frame, name, keys=keys) + return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype) # legacy names, with depreciation warnings and copied docs diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index b185d530e056c..1d581b00e4b3c 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -651,6 +651,14 @@ def test_get_schema(self): con=self.conn) self.assertTrue('CREATE' in create_sql) + def test_get_schema_dtypes(self): + float_frame = DataFrame({'a':[1.1,1.2], 'b':[2.1,2.2]}) + dtype = sqlalchemy.Integer if self.mode == 'sqlalchemy' else 'INTEGER' + create_sql = sql.get_schema(float_frame, 'test', 'sqlite', + con=self.conn, dtype={'b':dtype}) + self.assertTrue('CREATE' in create_sql) + self.assertTrue('INTEGER' in create_sql) + def test_chunksize_read(self): df = DataFrame(np.random.randn(22, 5), columns=list('abcde')) df.to_sql('test_chunksize', self.conn, index=False) @@ -1233,7 +1241,6 @@ def test_dtype(self): df.to_sql('dtype_test3', self.conn, dtype={'B': sqlalchemy.String(10)}) meta.reflect() sqltype = meta.tables['dtype_test3'].columns['B'].type - print(sqltype) self.assertTrue(isinstance(sqltype, sqlalchemy.String)) self.assertEqual(sqltype.length, 10) @@ -1262,6 +1269,36 @@ def test_notnull_dtype(self): self.assertTrue(isinstance(col_dict['Int'].type, sqltypes.Integer)) self.assertTrue(isinstance(col_dict['Float'].type, sqltypes.Float)) + def test_double_precision(self): + V = 1.23456789101112131415 + + df = DataFrame({'f32':Series([V,], dtype='float32'), + 'f64':Series([V,], dtype='float64'), + 'f64_as_f32':Series([V,], dtype='float64'), + 'i32':Series([5,], dtype='int32'), + 'i64':Series([5,], dtype='int64'), + }) + + df.to_sql('test_dtypes', self.conn, index=False, if_exists='replace', + dtype={'f64_as_f32':sqlalchemy.Float(precision=23)}) + res = sql.read_sql_table('test_dtypes', self.conn) + + # check precision of float64 + self.assertEqual(np.round(df['f64'].iloc[0],14), + np.round(res['f64'].iloc[0],14)) + + # check sql types + meta = sqlalchemy.schema.MetaData(bind=self.conn) + meta.reflect() + col_dict = meta.tables['test_dtypes'].columns + self.assertEqual(str(col_dict['f32'].type), + str(col_dict['f64_as_f32'].type)) + self.assertTrue(isinstance(col_dict['f32'].type, sqltypes.Float)) + self.assertTrue(isinstance(col_dict['f64'].type, sqltypes.Float)) + self.assertTrue(isinstance(col_dict['i32'].type, sqltypes.Integer)) + self.assertTrue(isinstance(col_dict['i64'].type, sqltypes.BigInteger)) + + class TestSQLiteAlchemy(_TestSQLAlchemy): """
Closes #9009 . @jorisvandenbossche -- do you think this should test/use single precision ? We could test for float32 perhaps? My own feeling is that this is the safer default.
https://api.github.com/repos/pandas-dev/pandas/pulls/9041
2014-12-08T08:17:20Z
2015-01-25T18:01:04Z
2015-01-25T18:01:04Z
2015-01-25T18:01:21Z
Return from to_timedelta is forced to dtype timedelta64[ns].
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index f034e0e223e6b..a2728c2d82d61 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -268,3 +268,5 @@ Bug Fixes - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) - Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) - Bug in plotting if sharex was enabled and index was a timeseries, would show labels on multiple axes (:issue:`3964`). + +- Bug where passing a unit to the TimedeltaIndex constructor applied the to nano-second conversion twice. (:issue:`9011`). diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 494a9cc95dc49..de23ddcc397d9 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -525,6 +525,22 @@ def conv(v): expected = TimedeltaIndex([ np.timedelta64(1,'D') ]*5) tm.assert_index_equal(result, expected) + # Test with lists as input when box=false + expected = np.array(np.arange(3)*1000000000, dtype='timedelta64[ns]') + result = to_timedelta(range(3), unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + result = to_timedelta(np.arange(3), unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + result = to_timedelta([0, 1, 2], unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + # Tests with fractional seconds as input: + expected = np.array([0, 500000000, 800000000, 1200000000], dtype='timedelta64[ns]') + result = to_timedelta([0., 0.5, 0.8, 1.2], unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + def testit(unit, transform): # array @@ -852,6 +868,13 @@ def test_constructor(self): pd.offsets.Second(3)]) tm.assert_index_equal(result,expected) + expected = TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02']) + tm.assert_index_equal(TimedeltaIndex(range(3), unit='s'), expected) + expected = TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:05', '0 days 00:00:09']) + tm.assert_index_equal(TimedeltaIndex([0, 5, 9], unit='s'), expected) + expected = TimedeltaIndex(['0 days 00:00:00.400', '0 days 00:00:00.450', '0 days 00:00:01.200']) + tm.assert_index_equal(TimedeltaIndex([400, 450, 1200], unit='ms'), expected) + def test_constructor_coverage(self): rng = timedelta_range('1 days', periods=10.5) exp = timedelta_range('1 days', periods=10) diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py index dc60f5024c9ed..91e75da1b551c 100644 --- a/pandas/tseries/timedeltas.py +++ b/pandas/tseries/timedeltas.py @@ -52,6 +52,7 @@ def _convert_listlike(arg, box, unit): value = np.array([ _get_string_converter(r, unit=unit)() for r in arg ],dtype='m8[ns]') except: value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit, coerce=coerce) for r in arg ]) + value = value.astype('timedelta64[ns]', copy=False) if box: from pandas import TimedeltaIndex
This is a revised change, fixing the issue I experienced (issue #9011). The proper change seems to be setting the dtype to `'timedelta64[ns]'`, as was already done for the other cases in the `to_timedelta` routine. I have also added more tests, and moved them to the `test_timedeltas` function (next to the other tests of the functionality of the constructor method). I have not looked too much at #8886, it is difficult for me to understand the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/9040
2014-12-08T07:38:36Z
2014-12-09T21:23:19Z
2014-12-09T21:23:19Z
2014-12-12T14:37:30Z
DOC: expand docs on sql type conversion
diff --git a/doc/source/io.rst b/doc/source/io.rst index f2d5924edac77..2ec61f7f00bd8 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3393,12 +3393,34 @@ the database using :func:`~pandas.DataFrame.to_sql`. data.to_sql('data', engine) -With some databases, writing large DataFrames can result in errors due to packet size limitations being exceeded. This can be avoided by setting the ``chunksize`` parameter when calling ``to_sql``. For example, the following writes ``data`` to the database in batches of 1000 rows at a time: +With some databases, writing large DataFrames can result in errors due to +packet size limitations being exceeded. This can be avoided by setting the +``chunksize`` parameter when calling ``to_sql``. For example, the following +writes ``data`` to the database in batches of 1000 rows at a time: .. ipython:: python data.to_sql('data_chunked', engine, chunksize=1000) +SQL data types +"""""""""""""" + +:func:`~pandas.DataFrame.to_sql` will try to map your data to an appropriate +SQL data type based on the dtype of the data. When you have columns of dtype +``object``, pandas will try to infer the data type. + +You can always override the default type by specifying the desired SQL type of +any of the columns by using the ``dtype`` argument. This argument needs a +dictionary mapping column names to SQLAlchemy types (or strings for the sqlite3 +fallback mode). +For example, specifying to use the sqlalchemy ``String`` type instead of the +default ``Text`` type for string columns: + +.. ipython:: python + + from sqlalchemy.types import String + data.to_sql('data_dtype', engine, dtype={'Col_1': String}) + .. note:: Due to the limited support for timedelta's in the different database @@ -3413,15 +3435,6 @@ With some databases, writing large DataFrames can result in errors due to packet Because of this, reading the database table back in does **not** generate a categorical. -.. note:: - - You can specify the SQL type of any of the columns by using the dtypes - parameter (a dictionary mapping column names to SQLAlchemy types). This - can be useful in cases where columns with NULL values are inferred by - Pandas to an excessively general datatype (e.g. a boolean column is is - inferred to be object because it has NULLs). - - Reading Tables ~~~~~~~~~~~~~~ @@ -3782,11 +3795,11 @@ is lost when exporting. *Stata* only supports string value labels, and so ``str`` is called on the categories when exporting data. Exporting ``Categorical`` variables with - non-string categories produces a warning, and can result a loss of + non-string categories produces a warning, and can result a loss of information if the ``str`` representations of the categories are not unique. Labeled data can similarly be imported from *Stata* data files as ``Categorical`` -variables using the keyword argument ``convert_categoricals`` (``True`` by default). +variables using the keyword argument ``convert_categoricals`` (``True`` by default). The keyword argument ``order_categoricals`` (``True`` by default) determines whether imported ``Categorical`` variables are ordered. diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 419885ad4159b..8e2c7a862362a 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -96,7 +96,16 @@ API changes Enhancements ~~~~~~~~~~~~ -- Added the ability to specify the SQL type of columns when writing a DataFrame to a database (:issue:`8778`). +- Added the ability to specify the SQL type of columns when writing a DataFrame + to a database (:issue:`8778`). + For example, specifying to use the sqlalchemy ``String`` type instead of the + default ``Text`` type for string columns: + + .. code-block:: + + from sqlalchemy.types import String + data.to_sql('data_dtype', engine, dtype={'Col_1': String}) + - Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. - Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. - Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d63643c53e6f4..0fc7171410152 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -954,8 +954,9 @@ def to_sql(self, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : Dictionary of column name to SQLAlchemy type, default None - Optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ from pandas.io import sql @@ -4128,7 +4129,7 @@ def func(self, axis=None, dtype=None, out=None, skipna=True, y = _values_from_object(self).copy() - if skipna and issubclass(y.dtype.type, + if skipna and issubclass(y.dtype.type, (np.datetime64, np.timedelta64)): result = accum_func(y, axis) mask = isnull(self) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 77527f867fad8..ea6239f080caa 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -518,8 +518,9 @@ def to_sql(frame, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column name to SQLAchemy type, default None - optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ if if_exists not in ('fail', 'replace', 'append'): @@ -1133,8 +1134,9 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column name to SQLAlchemy type, default None - Optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type. """ if dtype is not None: @@ -1468,8 +1470,9 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column_name to SQLite string type, default None - optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a string. """ if dtype is not None:
Some doc changes related to #8926 and #8973
https://api.github.com/repos/pandas-dev/pandas/pulls/9038
2014-12-07T21:21:55Z
2014-12-08T11:59:49Z
2014-12-08T11:59:49Z
2014-12-08T11:59:49Z
COMPAT: dateutil fixups for 2.3 (GH9021, GH8639)
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index 1fd2d7b8fa8e5..cf82733c6629d 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -104,12 +104,12 @@ def test_timestamp_tz_arg_dateutil(self): import dateutil from pandas.tslib import maybe_get_tz p = Period('1/1/2005', freq='M').to_timestamp(tz=maybe_get_tz('dateutil/Europe/Brussels')) - self.assertEqual(p.tz, dateutil.tz.gettz('Europe/Brussels')) + self.assertEqual(p.tz, dateutil.zoneinfo.gettz('Europe/Brussels')) def test_timestamp_tz_arg_dateutil_from_string(self): import dateutil p = Period('1/1/2005', freq='M').to_timestamp(tz='dateutil/Europe/Brussels') - self.assertEqual(p.tz, dateutil.tz.gettz('Europe/Brussels')) + self.assertEqual(p.tz, dateutil.zoneinfo.gettz('Europe/Brussels')) def test_timestamp_nat_tz(self): t = Period('NaT', freq='M').to_timestamp() diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index b9ccb76b59c59..1976eee96296c 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -37,8 +37,12 @@ cimport cython from datetime import timedelta, datetime from datetime import time as datetime_time + +# dateutil compat from dateutil.tz import (tzoffset, tzlocal as _dateutil_tzlocal, tzfile as _dateutil_tzfile, - tzutc as _dateutil_tzutc, gettz as _dateutil_gettz) + tzutc as _dateutil_tzutc) +from dateutil.zoneinfo import gettz as _dateutil_gettz + from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo from pandas.compat import parse_date, string_types, PY3, iteritems @@ -1258,7 +1262,7 @@ cpdef inline object maybe_get_tz(object tz): if isinstance(tz, string_types): if tz.startswith('dateutil/'): zone = tz[9:] - tz = _dateutil_gettz(tz[9:]) + tz = _dateutil_gettz(zone) # On Python 3 on Windows, the filename is not always set correctly. if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename: tz._filename = zone
fixes #9021 but going to reopen #8639
https://api.github.com/repos/pandas-dev/pandas/pulls/9036
2014-12-07T20:51:49Z
2014-12-07T22:26:13Z
2014-12-07T22:26:13Z
2014-12-08T14:46:53Z
DOC: fix categorical comparison example (GH8946)
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index d10524e5d392f..91cfa77bc618c 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -356,9 +356,9 @@ Comparisons Comparing categorical data with other objects is possible in three cases: * comparing equality (``==`` and ``!=``) to a list-like object (list, Series, array, - ...) of the same length as the categorical data or + ...) of the same length as the categorical data. * all comparisons (``==``, ``!=``, ``>``, ``>=``, ``<``, and ``<=``) of categorical data to - another categorical Series, when ``ordered==True`` and the `categories` are the same or + another categorical Series, when ``ordered==True`` and the `categories` are the same. * all comparisons of a categorical data to a scalar. All other comparisons, especially "non-equality" comparisons of two categoricals with different @@ -392,7 +392,8 @@ Equality comparisons work with any list-like object of same length and scalars: .. ipython:: python - cat == cat_base2 + cat == cat_base + cat == np.array([1,2,3]) cat == 2 This doesn't work because the categories are not the same:
See discussion https://github.com/pydata/pandas/pull/8946/files#r21376839
https://api.github.com/repos/pandas-dev/pandas/pulls/9035
2014-12-07T20:38:08Z
2014-12-07T21:42:53Z
2014-12-07T21:42:53Z
2014-12-07T21:42:53Z
Implement timedeltas for to_json
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py index 5732bc90573fd..75a6f22488b41 100644 --- a/pandas/io/tests/test_json/test_pandas.py +++ b/pandas/io/tests/test_json/test_pandas.py @@ -4,8 +4,8 @@ import os import numpy as np -import nose from pandas import Series, DataFrame, DatetimeIndex, Timestamp +from datetime import timedelta import pandas as pd read_json = pd.read_json @@ -601,7 +601,6 @@ def test_url(self): self.assertEqual(result[c].dtype, 'datetime64[ns]') def test_timedelta(self): - from datetime import timedelta converter = lambda x: pd.to_timedelta(x,unit='ms') s = Series([timedelta(23), timedelta(seconds=5)]) @@ -613,17 +612,32 @@ def test_timedelta(self): assert_frame_equal( frame, pd.read_json(frame.to_json()).apply(converter)) - def test_default_handler(self): - from datetime import timedelta - - frame = DataFrame([timedelta(23), timedelta(seconds=5), 42]) - self.assertRaises(OverflowError, frame.to_json) + frame = DataFrame({'a': [timedelta(23), timedelta(seconds=5)], + 'b': [1, 2], + 'c': pd.date_range(start='20130101', periods=2)}) + result = pd.read_json(frame.to_json(date_unit='ns')) + result['a'] = pd.to_timedelta(result.a, unit='ns') + result['c'] = pd.to_datetime(result.c) + assert_frame_equal(frame, result) + + def test_mixed_timedelta_datetime(self): + frame = DataFrame({'a': [timedelta(23), pd.Timestamp('20130101')]}, + dtype=object) + expected = pd.read_json(frame.to_json(date_unit='ns'), + dtype={'a': 'int64'}) + assert_frame_equal(DataFrame({'a': [pd.Timedelta(frame.a[0]).value, + pd.Timestamp(frame.a[1]).value]}), + expected) - expected = DataFrame([str(timedelta(23)), str(timedelta(seconds=5)), 42]) - assert_frame_equal( - expected, pd.read_json(frame.to_json(default_handler=str))) + def test_default_handler(self): + value = object() + frame = DataFrame({'a': ['a', value]}) + expected = frame.applymap(str) + result = pd.read_json(frame.to_json(default_handler=str)) + assert_frame_equal(expected, result) + def test_default_handler_raises(self): def my_handler_raises(obj): raise TypeError("raisin") - self.assertRaises(TypeError, frame.to_json, + self.assertRaises(TypeError, DataFrame({'a': [1, 2, object()]}).to_json, default_handler=my_handler_raises) diff --git a/pandas/src/datetime_helper.h b/pandas/src/datetime_helper.h index 8be5f59728bb3..8e188a431a086 100644 --- a/pandas/src/datetime_helper.h +++ b/pandas/src/datetime_helper.h @@ -1,6 +1,23 @@ #include "datetime.h" +#if PY_MAJOR_VERSION >= 3 +#define PyInt_AS_LONG PyLong_AsLong +#endif + void mangle_nat(PyObject *val) { PyDateTime_GET_MONTH(val) = -1; PyDateTime_GET_DAY(val) = -1; } + +long get_long_attr(PyObject *o, const char *attr) { + return PyInt_AS_LONG(PyObject_GetAttrString(o, attr)); +} + +double total_seconds(PyObject *td) { + // Python 2.6 compat + long microseconds = get_long_attr(td, "microseconds"); + long seconds = get_long_attr(td, "seconds"); + long days = get_long_attr(td, "days"); + long days_in_seconds = days * 24 * 3600; + return (microseconds + (seconds + days_in_seconds) * 1000000.0) / 1000000.0; +} diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index c1e9f8edcf423..00ba8975d58c8 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -41,11 +41,11 @@ Numeric decoder derived from from TCL library #include <numpy/arrayscalars.h> #include <np_datetime.h> #include <np_datetime_strings.h> +#include <datetime_helper.h> #include <numpy_helper.h> #include <numpy/npy_math.h> #include <math.h> #include <stdio.h> -#include <datetime.h> #include <ultrajson.h> static PyObject* type_decimal; @@ -154,6 +154,7 @@ enum PANDAS_FORMAT // import_array() compat #if (PY_VERSION_HEX >= 0x03000000) void *initObjToJSON(void) + #else void initObjToJSON(void) #endif @@ -1445,14 +1446,38 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) PRINTMARK(); pc->PyTypeToJSON = NpyDateTimeToJSON; - if (enc->datetimeIso) - { - tc->type = JT_UTF8; - } + tc->type = enc->datetimeIso ? JT_UTF8 : JT_LONG; + return; + } + else + if (PyDelta_Check(obj)) + { + long value; + + if (PyObject_HasAttrString(obj, "value")) + value = get_long_attr(obj, "value"); else + value = total_seconds(obj) * 1000000000; // nanoseconds per second + + exc = PyErr_Occurred(); + + if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { - tc->type = JT_LONG; + PRINTMARK(); + goto INVALID; } + + if (value == get_nat()) { + PRINTMARK(); + tc->type = JT_NULL; + return; + } + + GET_TC(tc)->longValue = value; + + PRINTMARK(); + pc->PyTypeToJSON = PyLongToINT64; + tc->type = JT_LONG; return; } else diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 4cb6c93bdf3d0..3a3c14ac0cc58 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -20,6 +20,9 @@ cdef extern from "Python.h": cdef PyTypeObject *Py_TYPE(object) int PySlice_Check(object) +cdef extern from "datetime_helper.h": + double total_seconds(object) + # this is our datetime.pxd from datetime cimport * from util cimport is_integer_object, is_float_object, is_datetime64_object, is_timedelta64_object @@ -2753,10 +2756,6 @@ cdef object _get_deltas(object tz): return utc_offset_cache[cache_key] -cdef double total_seconds(object td): # Python 2.6 compat - return ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) // - 10**6) - def tot_seconds(td): return total_seconds(td)
Closes #9027
https://api.github.com/repos/pandas-dev/pandas/pulls/9028
2014-12-06T22:27:31Z
2014-12-07T20:25:34Z
2014-12-07T20:25:34Z
2014-12-07T20:25:39Z
BUG: Fix Datareader dtypes if there are missing values from Google.
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 58dc1da214c05..7d54bc73e9ae6 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -222,3 +222,4 @@ Bug Fixes - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) +- Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) diff --git a/pandas/io/data.py b/pandas/io/data.py index 0827d74191842..3d92d383badf8 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -166,7 +166,7 @@ def _retry_read_url(url, retry_count, pause, name): pass else: rs = read_csv(StringIO(bytes_to_str(lines)), index_col=0, - parse_dates=True)[::-1] + parse_dates=True, na_values='-')[::-1] # Yahoo! Finance sometimes does this awesome thing where they # return 2 rows for the most recent business day if len(rs) > 2 and rs.index[-1] == rs.index[-2]: # pragma: no cover diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 3fca0393339fc..a65722dc76556 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -118,8 +118,8 @@ def test_get_multi2(self): assert_n_failed_equals_n_null_columns(w, result) def test_dtypes(self): - #GH3995 - data = web.get_data_google('MSFT', 'JAN-01-12', 'JAN-31-12') + #GH3995, #GH8980 + data = web.get_data_google('F', start='JAN-01-10', end='JAN-27-13') assert np.issubdtype(data.Open.dtype, np.number) assert np.issubdtype(data.Close.dtype, np.number) assert np.issubdtype(data.Low.dtype, np.number)
Fixes #8980
https://api.github.com/repos/pandas-dev/pandas/pulls/9025
2014-12-06T20:34:01Z
2014-12-07T00:07:23Z
2014-12-07T00:07:23Z
2014-12-07T00:07:27Z
Make Timestamp('now') equivalent to Timestamp.now()
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d64dbf6e14345..4468b267e9d7f 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -62,6 +62,9 @@ API changes - Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) +- Timestamp('now') is now equivalent to Timestamp.now() in that it returns the local time rather than UTC. Also, Timestamp('today') is now + equivalent to Timestamp.today() and both have tz as a possible argument. (:issue:`9000`) + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 2e59febb2c62b..ad0ef67b5aca2 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -301,6 +301,36 @@ def test_barely_oob_dts(self): def test_utc_z_designator(self): self.assertEqual(get_timezone(Timestamp('2014-11-02 01:00Z').tzinfo), 'UTC') + def test_now(self): + # #9000 + ts_from_string = Timestamp('now') + ts_from_method = Timestamp.now() + ts_datetime = datetime.datetime.now() + + ts_from_string_tz = Timestamp('now', tz='US/Eastern') + ts_from_method_tz = Timestamp.now(tz='US/Eastern') + + # Check that the delta between the times is less than 1s (arbitrarily small) + delta = Timedelta(seconds=1) + self.assertTrue((ts_from_method - ts_from_string) < delta) + self.assertTrue((ts_from_method_tz - ts_from_string_tz) < delta) + self.assertTrue((ts_from_string_tz.tz_localize(None) - ts_from_string) < delta) + + def test_today(self): + + ts_from_string = Timestamp('today') + ts_from_method = Timestamp.today() + ts_datetime = datetime.datetime.today() + + ts_from_string_tz = Timestamp('today', tz='US/Eastern') + ts_from_method_tz = Timestamp.today(tz='US/Eastern') + + # Check that the delta between the times is less than 1s (arbitrarily small) + delta = Timedelta(seconds=1) + self.assertTrue((ts_from_method - ts_from_string) < delta) + self.assertTrue((ts_datetime - ts_from_method) < delta) + self.assertTrue((ts_datetime - ts_from_method) < delta) + self.assertTrue((ts_from_string_tz.tz_localize(None) - ts_from_string) < delta) class TestDatetimeParsingWrappers(tm.TestCase): def test_does_not_convert_mixed_integer(self): diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 4cb6c93bdf3d0..ae694840d0195 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -173,9 +173,9 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): result[i] = NaT else: if box: - result[i] = Timedelta(value) + result[i] = Timedelta(value) else: - result[i] = timedelta(microseconds=int(value)/1000) + result[i] = timedelta(microseconds=int(value)/1000) return result @@ -216,15 +216,32 @@ class Timestamp(_Timestamp): @classmethod def now(cls, tz=None): - """ compat now with datetime """ + """ + Return the current time in the local timezone. Equivalent + to datetime.now([tz]) + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ if isinstance(tz, basestring): tz = maybe_get_tz(tz) return cls(datetime.now(tz)) @classmethod - def today(cls): - """ compat today with datetime """ - return cls(datetime.today()) + def today(cls, tz=None): + """ + Return the current time in the local timezone. This differs + from datetime.today() in that it can be localized to a + passed timezone. + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ + return cls.now(tz) @classmethod def utcnow(cls): @@ -1021,6 +1038,14 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if util.is_string_object(ts): if ts in _nat_strings: ts = NaT + elif ts == 'now': + # Issue 9000, we short-circuit rather than going + # into np_datetime_strings which returns utc + ts = Timestamp.now(tz) + elif ts == 'today': + # Issue 9000, we short-circuit rather than going + # into np_datetime_strings which returns a normalized datetime + ts = Timestamp.today(tz) else: try: _string_to_dts(ts, &obj.dts, &out_local, &out_tzoffset)
closes #9000 I opted to not change np_datetime_strings but instead short-circuit in Timestamp. I don't have a strong preference one way or another.
https://api.github.com/repos/pandas-dev/pandas/pulls/9022
2014-12-06T18:27:51Z
2014-12-07T21:01:06Z
2014-12-07T21:01:06Z
2014-12-22T14:55:29Z
reindex multi-index at level with reordered labels
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d64dbf6e14345..6e065c5818616 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -119,6 +119,7 @@ Bug Fixes - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) +- Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) - Fix negative step support for label-based slices (:issue:`8753`) diff --git a/pandas/core/index.py b/pandas/core/index.py index 7d9f772126483..be17c36e65675 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1828,13 +1828,41 @@ def _join_non_unique(self, other, how='left', return_indexers=False): else: return join_index - def _join_level(self, other, level, how='left', return_indexers=False): + def _join_level(self, other, level, how='left', + return_indexers=False, + keep_order=True): """ The join method *only* affects the level of the resulting MultiIndex. Otherwise it just exactly aligns the Index data to the - labels of the level in the MultiIndex. The order of the data indexed by - the MultiIndex will not be changed (currently) - """ + labels of the level in the MultiIndex. If `keep_order` == True, the + order of the data indexed by the MultiIndex will not be changed; + otherwise, it will tie out with `other`. + """ + from pandas.algos import groupsort_indexer + + def _get_leaf_sorter(labels): + ''' + returns sorter for the inner most level while preserving the + order of higher levels + ''' + if labels[0].size == 0: + return np.empty(0, dtype='int64') + + if len(labels) == 1: + lab = com._ensure_int64(labels[0]) + sorter, _ = groupsort_indexer(lab, 1 + lab.max()) + return sorter + + # find indexers of begining of each set of + # same-key labels w.r.t all but last level + tic = labels[0][:-1] != labels[0][1:] + for lab in labels[1:-1]: + tic |= lab[:-1] != lab[1:] + + starts = np.hstack(([True], tic, [True])).nonzero()[0] + lab = com._ensure_int64(labels[-1]) + return lib.get_level_sorter(lab, starts) + if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): raise TypeError('Join on level between two MultiIndex objects ' 'is ambiguous') @@ -1849,33 +1877,69 @@ def _join_level(self, other, level, how='left', return_indexers=False): level = left._get_level_number(level) old_level = left.levels[level] + if not right.is_unique: + raise NotImplementedError('Index._join_level on non-unique index ' + 'is not implemented') + new_level, left_lev_indexer, right_lev_indexer = \ old_level.join(right, how=how, return_indexers=True) - if left_lev_indexer is not None: + if left_lev_indexer is None: + if keep_order or len(left) == 0: + left_indexer = None + join_index = left + else: # sort the leaves + left_indexer = _get_leaf_sorter(left.labels[:level + 1]) + join_index = left[left_indexer] + + else: left_lev_indexer = com._ensure_int64(left_lev_indexer) rev_indexer = lib.get_reverse_indexer(left_lev_indexer, len(old_level)) new_lev_labels = com.take_nd(rev_indexer, left.labels[level], allow_fill=False) - omit_mask = new_lev_labels != -1 new_labels = list(left.labels) new_labels[level] = new_lev_labels - if not omit_mask.all(): - new_labels = [lab[omit_mask] for lab in new_labels] - new_levels = list(left.levels) new_levels[level] = new_level - join_index = MultiIndex(levels=new_levels, labels=new_labels, - names=left.names, verify_integrity=False) - left_indexer = np.arange(len(left))[new_lev_labels != -1] - else: - join_index = left - left_indexer = None + if keep_order: # just drop missing values. o.w. keep order + left_indexer = np.arange(len(left)) + mask = new_lev_labels != -1 + if not mask.all(): + new_labels = [lab[mask] for lab in new_labels] + left_indexer = left_indexer[mask] + + else: # tie out the order with other + if level == 0: # outer most level, take the fast route + ngroups = 1 + new_lev_labels.max() + left_indexer, counts = groupsort_indexer(new_lev_labels, + ngroups) + # missing values are placed first; drop them! + left_indexer = left_indexer[counts[0]:] + new_labels = [lab[left_indexer] for lab in new_labels] + + else: # sort the leaves + mask = new_lev_labels != -1 + mask_all = mask.all() + if not mask_all: + new_labels = [lab[mask] for lab in new_labels] + + left_indexer = _get_leaf_sorter(new_labels[:level + 1]) + new_labels = [lab[left_indexer] for lab in new_labels] + + # left_indexers are w.r.t masked frame. + # reverse to original frame! + if not mask_all: + left_indexer = mask.nonzero()[0][left_indexer] + + join_index = MultiIndex(levels=new_levels, + labels=new_labels, + names=left.names, + verify_integrity=False) if right_lev_indexer is not None: right_indexer = com.take_nd(right_lev_indexer, @@ -3925,7 +3989,8 @@ def reindex(self, target, method=None, level=None, limit=None): else: target = _ensure_index(target) target, indexer, _ = self._join_level(target, level, how='right', - return_indexers=True) + return_indexers=True, + keep_order=False) else: if self.equals(target): indexer = None diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 2a5b93d111acc..71aeaf0895035 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -1138,6 +1138,27 @@ def row_bool_subset_object(ndarray[object, ndim=2] values, return out +@cython.boundscheck(False) +@cython.wraparound(False) +def get_level_sorter(ndarray[int64_t, ndim=1] label, + ndarray[int64_t, ndim=1] starts): + """ + argsort for a single level of a multi-index, keeping the order of higher + levels unchanged. `starts` points to starts of same-key indices w.r.t + to leading levels; equivalent to: + np.hstack([label[starts[i]:starts[i+1]].argsort(kind='mergesort') + + starts[i] for i in range(len(starts) - 1)]) + """ + cdef: + int64_t l, r + Py_ssize_t i + ndarray[int64_t, ndim=1] out = np.empty(len(label), dtype=np.int64) + + for i in range(len(starts) - 1): + l, r = starts[i], starts[i + 1] + out[l:r] = l + label[l:r].argsort(kind='mergesort') + + return out def group_count(ndarray[int64_t] values, Py_ssize_t size): cdef: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 67f86a1c6cb7e..40823537dbc04 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -1897,6 +1897,66 @@ def test_reversed_reindex_ffill_raises(self): self.assertRaises(ValueError, df.reindex, dr[::-1], method='ffill') self.assertRaises(ValueError, df.reindex, dr[::-1], method='bfill') + def test_reindex_level(self): + from itertools import permutations + icol = ['jim', 'joe', 'jolie'] + + def verify_first_level(df, level, idx): + f = lambda val: 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) + assert_frame_equal(left, right) + + def verify(df, level, idx, indexer): + left = df.set_index(icol).reindex(idx, level=level) + right = df.iloc[indexer].set_index(icol) + assert_frame_equal(left, right) + + df = pd.DataFrame({'jim':list('B' * 4 + 'A' * 2 + 'C' * 3), + 'joe':list('abcdeabcd')[::-1], + 'jolie':[10, 20, 30] * 3, + 'joline': np.random.randint(0, 1000, 9)}) + + target = [['C', 'B', 'A'], ['F', 'C', 'A', 'D'], ['A'], ['D', 'F'], + ['A', 'B', 'C'], ['C', 'A', 'B'], ['C', 'B'], ['C', 'A'], + ['A', 'B'], ['B', 'A', 'C'], ['A', 'C', 'B']] + + for idx in target: + verify_first_level(df, 'jim', idx) + + verify(df, 'joe', list('abcde'), [3, 2, 1, 0, 5, 4, 8, 7, 6]) + verify(df, 'joe', list('abcd'), [3, 2, 1, 0, 5, 8, 7, 6]) + verify(df, 'joe', list('abc'), [3, 2, 1, 8, 7, 6]) + verify(df, 'joe', list('eca'), [1, 3, 4, 6, 8]) + verify(df, 'joe', list('edc'), [0, 1, 4, 5, 6]) + verify(df, 'joe', list('eadbc'), [3, 0, 2, 1, 4, 5, 8, 7, 6]) + verify(df, 'joe', list('edwq'), [0, 4, 5]) + verify(df, 'joe', list('wq'), []) + + df = DataFrame({'jim':['mid'] * 5 + ['btm'] * 8 + ['top'] * 7, + 'joe':['3rd'] * 2 + ['1st'] * 3 + ['2nd'] * 3 + + ['1st'] * 2 + ['3rd'] * 3 + ['1st'] * 2 + + ['3rd'] * 3 + ['2nd'] * 2, + 'jolie':np.random.randint(0, 1000, 20), + 'joline': np.random.randn(20).round(3) * 10}) + + for idx in permutations(df['jim'].unique()): + for i in range(3): + verify_first_level(df, 'jim', idx[:i+1]) + + i = [2,3,4,0,1,8,9,5,6,7,10,11,12,13,14,18,19,15,16,17] + verify(df, 'joe', ['1st', '2nd', '3rd'], i) + + i = [0,1,2,3,4,10,11,12,5,6,7,8,9,15,16,17,18,19,13,14] + verify(df, 'joe', ['3rd', '2nd', '1st'], i) + + i = [0,1,5,6,7,10,11,12,18,19,15,16,17] + verify(df, 'joe', ['2nd', '3rd'], i) + + i = [0,1,2,3,4,10,11,12,8,9,15,16,17,13,14] + verify(df, 'joe', ['3rd', '1st'], i) + def test_getitem_ix_float_duplicates(self): df = pd.DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list('abc'))
closes https://github.com/pydata/pandas/issues/4088 on branch: ``` >>> df vals first second third mid 3rd 992 1.96 562 12.06 1st 73 -6.46 818 -15.75 658 5.90 btm 2nd 915 9.75 474 -1.47 905 -6.03 1st 717 8.01 909 -21.12 3rd 616 11.91 675 1.06 579 -4.01 top 1st 241 1.79 363 1.71 3rd 677 13.38 238 -16.77 407 17.19 2nd 728 -21.55 36 8.09 >>> df.reindex(['top', 'mid', 'btm'], level='first') vals first second third top 1st 241 1.79 363 1.71 3rd 677 13.38 238 -16.77 407 17.19 2nd 728 -21.55 36 8.09 mid 3rd 992 1.96 562 12.06 1st 73 -6.46 818 -15.75 658 5.90 btm 2nd 915 9.75 474 -1.47 905 -6.03 1st 717 8.01 909 -21.12 3rd 616 11.91 675 1.06 579 -4.01 >>> df.reindex(['1st', '2nd', '3rd'], level='second') vals first second third mid 1st 73 -6.46 818 -15.75 658 5.90 3rd 992 1.96 562 12.06 btm 1st 717 8.01 909 -21.12 2nd 915 9.75 474 -1.47 905 -6.03 3rd 616 11.91 675 1.06 579 -4.01 top 1st 241 1.79 363 1.71 2nd 728 -21.55 36 8.09 3rd 677 13.38 238 -16.77 407 17.19 >>> df.reindex(['top', 'btm'], level='first').reindex(['1st', '2nd'], level='second') vals first second third top 1st 241 1.79 363 1.71 2nd 728 -21.55 36 8.09 btm 1st 717 8.01 909 -21.12 2nd 915 9.75 474 -1.47 905 -6.03 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/9019
2014-12-06T15:51:22Z
2014-12-07T00:18:23Z
2014-12-07T00:18:23Z
2014-12-07T00:29:18Z
BUG: Prevent index header column from being added on MultiIndex when ind...
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a1a353980f7aa..596bb841f16c9 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -155,6 +155,7 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) +- Fixed Multindex to_html index=False adds an extra column (:issue:`8452`) diff --git a/pandas/core/format.py b/pandas/core/format.py index dbfe78d93bdcd..a17c45b70c74b 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -959,6 +959,10 @@ def _column_header(): name = self.columns.names[lnum] row = [''] * (row_levels - 1) + ['' if name is None else com.pprint_thing(name)] + + if row == [""] and self.fmt.index is False: + row = [] + tags = {} j = len(row) for i, v in enumerate(values): diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index ba3daf1b52045..80f1733ab4be5 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -571,6 +571,47 @@ def test_to_html_escape_disabled(self): </table>""" self.assertEqual(xp, rs) + def test_to_html_multiindex_index_false(self): + # issue 8452 + df = pd.DataFrame({ + 'a': range(2), + 'b': range(3, 5), + 'c': range(5, 7), + 'd': range(3, 5)} + ) + df.columns = pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']]) + result = df.to_html(index=False) + expected = """\ +<table border="1" class="dataframe"> + <thead> + <tr> + <th colspan="2" halign="left">a</th> + <th colspan="2" halign="left">b</th> + </tr> + <tr> + <th>c</th> + <th>d</th> + <th>c</th> + <th>d</th> + </tr> + </thead> + <tbody> + <tr> + <td> 0</td> + <td> 3</td> + <td> 5</td> + <td> 3</td> + </tr> + <tr> + <td> 1</td> + <td> 4</td> + <td> 6</td> + <td> 4</td> + </tr> + </tbody> +</table>""" + self.assertEqual(result, expected) + def test_to_html_multiindex_sparsify_false_multi_sparse(self): with option_context('display.multi_sparse', False): index = pd.MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]],
Fix for #8452 Index column was added when index=False.
https://api.github.com/repos/pandas-dev/pandas/pulls/9018
2014-12-06T01:01:08Z
2014-12-07T22:27:17Z
2014-12-07T22:27:17Z
2014-12-07T22:27:24Z
ENH: Implement Series.StringMethod.slice_replace
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 839a055bf2a63..e58bb6f703b3d 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -62,6 +62,8 @@ Enhancements - Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`) - Added time interval selection in get_data_yahoo (:issue:`9071`) +- Added ``Series.str.slice_replace()``, which previously raised NotImplementedError (:issue:`8888`) + Performance ~~~~~~~~~~~ diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 2c2a98c0c5434..9d4994e0f2de9 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -687,15 +687,34 @@ def str_slice(arr, start=None, stop=None, step=None): def str_slice_replace(arr, start=None, stop=None, repl=None): """ + Replace a slice of each string with another string. Parameters ---------- + start : int or None + stop : int or None + repl : str or None Returns ------- replaced : array """ - raise NotImplementedError + if repl is None: + repl = '' + + def f(x): + if x[start:stop] == '': + local_stop = start + else: + local_stop = stop + y = '' + if start is not None: + y += x[:start] + y += repl + if stop is not None: + y += x[local_stop:] + return y + return _na_map(f, arr) def str_strip(arr, to_strip=None): @@ -998,9 +1017,10 @@ def slice(self, start=None, stop=None, step=None): result = str_slice(self.series, start, stop, step) return self._wrap_result(result) - @copy(str_slice) - def slice_replace(self, i=None, j=None): - raise NotImplementedError + @copy(str_slice_replace) + def slice_replace(self, start=None, stop=None, repl=None): + result = str_slice_replace(self.series, start, stop, repl) + return self._wrap_result(result) @copy(str_decode) def decode(self, encoding, errors="strict"): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 06f507a50f785..50dba3bc7218a 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -963,7 +963,39 @@ def test_slice(self): tm.assert_series_equal(result, exp) def test_slice_replace(self): - pass + values = Series(['short', 'a bit longer', 'evenlongerthanthat', '', NA]) + + exp = Series(['shrt', 'a it longer', 'evnlongerthanthat', '', NA]) + result = values.str.slice_replace(2, 3) + tm.assert_series_equal(result, exp) + + exp = Series(['shzrt', 'a zit longer', 'evznlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 3, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shzort', 'a zbit longer', 'evzenlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 2, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shzort', 'a zbit longer', 'evzenlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 1, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shorz', 'a bit longez', 'evenlongerthanthaz', 'z', NA]) + result = values.str.slice_replace(-1, None, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['zrt', 'zer', 'zat', 'z', NA]) + result = values.str.slice_replace(None, -2, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shortz', 'a bit znger', 'evenlozerthanthat', 'z', NA]) + result = values.str.slice_replace(6, 8, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['zrt', 'a zit longer', 'evenlongzerthanthat', 'z', NA]) + result = values.str.slice_replace(-10, 3, 'z') + tm.assert_series_equal(result, exp) def test_strip_lstrip_rstrip(self): values = Series([' aa ', ' bb \n', NA, 'cc '])
closes #8888 This does not implement immerrr's suggestion of implementing `__setitem__`, as all `StringMethod` methods return a new `Series` (or `DataFrame`) rather than mutating.
https://api.github.com/repos/pandas-dev/pandas/pulls/9014
2014-12-05T19:57:58Z
2015-01-08T01:59:16Z
2015-01-08T01:59:16Z
2015-01-08T02:01:29Z
BUG: Bug in using a pd.Grouper(key=...) with no level/axis or level only (GH8795, GH8866)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a1a353980f7aa..10b23605cca85 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -98,6 +98,7 @@ Bug Fixes - Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) - Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) +- Bug in using a ``pd.Grouper(key=...)`` with no level/axis or level only (:issue:`8795`, :issue:`8866`) - Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) - Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) - Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4b85da1b7b224..4c221cc27fdce 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -168,7 +168,7 @@ class Grouper(object): freq : string / freqency object, defaults to None This will groupby the specified frequency if the target selection (via key or level) is a datetime-like object - axis : number/name of the axis, defaults to None + axis : number/name of the axis, defaults to 0 sort : boolean, default to False whether to sort the resulting labels @@ -198,7 +198,7 @@ def __new__(cls, *args, **kwargs): cls = TimeGrouper return super(Grouper, cls).__new__(cls) - def __init__(self, key=None, level=None, freq=None, axis=None, sort=False): + def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): self.key=key self.level=level self.freq=freq @@ -228,6 +228,8 @@ def _get_grouper(self, obj): """ self._set_grouper(obj) + self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key], axis=self.axis, + level=self.level, sort=self.sort) return self.binner, self.grouper, self.obj def _set_grouper(self, obj, sort=False): diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index a9ea64f54f51e..f60cf0a184832 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -373,6 +373,39 @@ def test_grouper_multilevel_freq(self): pd.Grouper(level=1, freq='W')]).sum() assert_frame_equal(result, expected) + def test_grouper_creation_bug(self): + + # GH 8795 + df = DataFrame({'A':[0,0,1,1,2,2], 'B':[1,2,3,4,5,6]}) + g = df.groupby('A') + expected = g.sum() + + g = df.groupby(pd.Grouper(key='A')) + result = g.sum() + assert_frame_equal(result, expected) + + result = g.apply(lambda x: x.sum()) + assert_frame_equal(result, expected) + + g = df.groupby(pd.Grouper(key='A',axis=0)) + result = g.sum() + assert_frame_equal(result, expected) + + # GH8866 + s = Series(np.arange(8), + index=pd.MultiIndex.from_product([list('ab'), + range(2), + date_range('20130101',periods=2)], + names=['one','two','three'])) + result = s.groupby(pd.Grouper(level='three',freq='M')).sum() + expected = Series([28],index=Index([Timestamp('2013-01-31')],freq='M',name='three')) + assert_series_equal(result, expected) + + # just specifying a level breaks + result = s.groupby(pd.Grouper(level='one')).sum() + expected = s.groupby(level='one').sum() + assert_series_equal(result, expected) + def test_grouper_iter(self): self.assertEqual(sorted(self.df.groupby('A').grouper), ['bar', 'foo'])
closes #8795 closes #8866
https://api.github.com/repos/pandas-dev/pandas/pulls/9008
2014-12-05T01:58:13Z
2014-12-05T02:34:01Z
2014-12-05T02:34:01Z
2014-12-05T02:34:01Z
Fix groupby().transform() example in cookbook.rst
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 8378873db9a65..81fe4aac51dd7 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -489,10 +489,10 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to .. ipython:: python def GrowUp(x): - avg_weight = sum(x[x.size == 'S'].weight * 1.5) - avg_weight += sum(x[x.size == 'M'].weight * 1.25) - avg_weight += sum(x[x.size == 'L'].weight) - avg_weight = avg_weight / len(x) + avg_weight = sum(x[x['size'] == 'S'].weight * 1.5) + avg_weight += sum(x[x['size'] == 'M'].weight * 1.25) + avg_weight += sum(x[x['size'] == 'L'].weight) + avg_weight /= len(x) return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult']) expected_df = gb.apply(GrowUp)
@jorisvandenbossche : Fixes code in example, and makes final averaging by len(x) stylistically similar to previous adds. New pull request replacing my earlier one, which contained some other erroneous commits. closes #8944
https://api.github.com/repos/pandas-dev/pandas/pulls/9007
2014-12-05T00:24:42Z
2014-12-05T02:11:13Z
2014-12-05T02:11:13Z
2014-12-05T06:11:47Z
REGR: Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (GH8890)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..4fbf7cbfa7c98 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -118,6 +118,7 @@ Bug Fixes s.loc['c':'a':-1] - Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) +- Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (:issue:`8890`) - Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) - 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`). diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 436f9f3b9c9b3..12e10a71c67b2 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2313,6 +2313,27 @@ def test_map(self): exp = [f(x) for x in rng] self.assert_numpy_array_equal(result, exp) + + def test_iteration_preserves_tz(self): + + tm._skip_if_no_dateutil() + + # GH 8890 + import dateutil + index = date_range("2012-01-01", periods=3, freq='H', tz='US/Eastern') + + for i, ts in enumerate(index): + result = ts + expected = index[i] + self.assertEqual(result, expected) + + index = date_range("2012-01-01", periods=3, freq='H', tz=dateutil.tz.tzoffset(None, -28800)) + + for i, ts in enumerate(index): + result = ts + expected = index[i] + self.assertEqual(result, expected) + def test_misc_coverage(self): rng = date_range('1/1/2000', periods=5) result = rng.groupby(rng.day) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 8efc174d6890b..02c1ae82a7fca 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -122,7 +122,9 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, offset=None, box=False): else: pandas_datetime_to_datetimestruct(value, PANDAS_FR_ns, &dts) dt = func_create(value, dts, tz, offset) - result[i] = dt + tz.utcoffset(dt) + if not box: + dt = dt + tz.utcoffset(dt) + result[i] = dt else: trans = _get_transitions(tz) deltas = _get_deltas(tz)
closes #8890
https://api.github.com/repos/pandas-dev/pandas/pulls/8990
2014-12-04T01:36:00Z
2014-12-04T02:47:31Z
2014-12-04T02:47:31Z
2014-12-04T02:47:31Z
FIX: use decorator to append read_frame/frame_query docstring (GH8315)
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index bb810b8509ef3..77527f867fad8 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -19,6 +19,7 @@ from pandas.core.common import isnull from pandas.core.base import PandasObject from pandas.tseries.tools import to_datetime +from pandas.util.decorators import Appender from contextlib import contextmanager @@ -1533,6 +1534,7 @@ def get_schema(frame, name, flavor='sqlite', keys=None, con=None): # legacy names, with depreciation warnings and copied docs +@Appender(read_sql.__doc__, join='\n') def read_frame(*args, **kwargs): """DEPRECATED - use read_sql """ @@ -1540,6 +1542,7 @@ def read_frame(*args, **kwargs): return read_sql(*args, **kwargs) +@Appender(read_sql.__doc__, join='\n') def frame_query(*args, **kwargs): """DEPRECATED - use read_sql """ @@ -1587,8 +1590,3 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs): index = kwargs.pop('index', False) return to_sql(frame, name, con, flavor=flavor, if_exists=if_exists, index=index, **kwargs) - - -# Append wrapped function docstrings -read_frame.__doc__ += read_sql.__doc__ -frame_query.__doc__ += read_sql.__doc__
Closes #8315
https://api.github.com/repos/pandas-dev/pandas/pulls/8988
2014-12-03T22:51:12Z
2014-12-04T08:27:53Z
2014-12-04T08:27:53Z
2014-12-04T10:43:27Z
BUG: Dynamically created table names allow SQL injection
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index b3ac58a9fb84a..7a47cc68fb627 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -106,6 +106,7 @@ Enhancements - ``tseries.frequencies.to_offset()`` now accepts ``Timedelta`` as input (:issue:`9064`) - ``Timedelta`` will now accept nanoseconds keyword in constructor (:issue:`9273`) +- SQL code now safely escapes table and column names (:issue:`8986`) Performance ~~~~~~~~~~~ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index b4318bdc2a3bf..87c86e8ef91a8 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1239,18 +1239,58 @@ def _create_sql_schema(self, frame, table_name, keys=None): } +def _get_unicode_name(name): + try: + uname = name.encode("utf-8", "strict").decode("utf-8") + except UnicodeError: + raise ValueError("Cannot convert identifier to UTF-8: '%s'" % name) + return uname + +def _get_valid_mysql_name(name): + # Filter for unquoted identifiers + # See http://dev.mysql.com/doc/refman/5.0/en/identifiers.html + uname = _get_unicode_name(name) + if not len(uname): + raise ValueError("Empty table or column name specified") + + basere = r'[0-9,a-z,A-Z$_]' + for c in uname: + if not re.match(basere, c): + if not (0x80 < ord(c) < 0xFFFF): + raise ValueError("Invalid MySQL identifier '%s'" % uname) + if not re.match(r'[^0-9]', uname): + raise ValueError('MySQL identifier cannot be entirely numeric') + + return '`' + uname + '`' + + +def _get_valid_sqlite_name(name): + # See http://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python + # Ensure the string can be encoded as UTF-8. + # Ensure the string does not include any NUL characters. + # Replace all " with "". + # Wrap the entire thing in double quotes. + + uname = _get_unicode_name(name) + if not len(uname): + raise ValueError("Empty table or column name specified") + + nul_index = uname.find("\x00") + if nul_index >= 0: + raise ValueError('SQLite identifier cannot contain NULs') + return '"' + uname.replace('"', '""') + '"' + + # SQL enquote and wildcard symbols -_SQL_SYMB = { - 'mysql': { - 'br_l': '`', - 'br_r': '`', - 'wld': '%s' - }, - 'sqlite': { - 'br_l': '[', - 'br_r': ']', - 'wld': '?' - } +_SQL_WILDCARD = { + 'mysql': '%s', + 'sqlite': '?' +} + +# Validate and return escaped identifier +_SQL_GET_IDENTIFIER = { + 'mysql': _get_valid_mysql_name, + 'sqlite': _get_valid_sqlite_name, } @@ -1276,18 +1316,17 @@ def _execute_create(self): def insert_statement(self): names = list(map(str, self.frame.columns)) flv = self.pd_sql.flavor - br_l = _SQL_SYMB[flv]['br_l'] # left val quote char - br_r = _SQL_SYMB[flv]['br_r'] # right val quote char - wld = _SQL_SYMB[flv]['wld'] # wildcard char + wld = _SQL_WILDCARD[flv] # wildcard char + escape = _SQL_GET_IDENTIFIER[flv] if self.index is not None: [names.insert(0, idx) for idx in self.index[::-1]] - bracketed_names = [br_l + column + br_r for column in names] + bracketed_names = [escape(column) for column in names] col_names = ','.join(bracketed_names) wildcards = ','.join([wld] * len(names)) insert_statement = 'INSERT INTO %s (%s) VALUES (%s)' % ( - self.name, col_names, wildcards) + escape(self.name), col_names, wildcards) return insert_statement def _execute_insert(self, conn, keys, data_iter): @@ -1309,29 +1348,28 @@ def _create_table_setup(self): warnings.warn(_SAFE_NAMES_WARNING) flv = self.pd_sql.flavor + escape = _SQL_GET_IDENTIFIER[flv] - br_l = _SQL_SYMB[flv]['br_l'] # left val quote char - br_r = _SQL_SYMB[flv]['br_r'] # right val quote char + create_tbl_stmts = [escape(cname) + ' ' + ctype + for cname, ctype, _ in column_names_and_types] - create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, col_type) - for cname, col_type, _ in column_names_and_types] if self.keys is not None and len(self.keys): - cnames_br = ",".join([br_l + c + br_r for c in self.keys]) + cnames_br = ",".join([escape(c) for c in self.keys]) create_tbl_stmts.append( "CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format( tbl=self.name, cnames_br=cnames_br)) - create_stmts = ["CREATE TABLE " + self.name + " (\n" + + create_stmts = ["CREATE TABLE " + escape(self.name) + " (\n" + ',\n '.join(create_tbl_stmts) + "\n)"] ix_cols = [cname for cname, _, is_index in column_names_and_types if is_index] if len(ix_cols): cnames = "_".join(ix_cols) - cnames_br = ",".join([br_l + c + br_r for c in ix_cols]) + cnames_br = ",".join([escape(c) for c in ix_cols]) create_stmts.append( - "CREATE INDEX ix_{tbl}_{cnames} ON {tbl} ({cnames_br})".format( - tbl=self.name, cnames=cnames, cnames_br=cnames_br)) + "CREATE INDEX " + escape("ix_"+self.name+"_"+cnames) + + "ON " + escape(self.name) + " (" + cnames_br + ")") return create_stmts @@ -1505,19 +1543,23 @@ def to_sql(self, frame, name, if_exists='fail', index=True, table.insert(chunksize) def has_table(self, name, schema=None): + escape = _SQL_GET_IDENTIFIER[self.flavor] + esc_name = escape(name) + wld = _SQL_WILDCARD[self.flavor] flavor_map = { 'sqlite': ("SELECT name FROM sqlite_master " - "WHERE type='table' AND name='%s';") % name, - 'mysql': "SHOW TABLES LIKE '%s'" % name} + "WHERE type='table' AND name=%s;") % wld, + 'mysql': "SHOW TABLES LIKE %s" % wld} query = flavor_map.get(self.flavor) - return len(self.execute(query).fetchall()) > 0 + return len(self.execute(query, [name,]).fetchall()) > 0 def get_table(self, table_name, schema=None): return None # not supported in fallback mode def drop_table(self, name, schema=None): - drop_sql = "DROP TABLE %s" % name + escape = _SQL_GET_IDENTIFIER[self.flavor] + drop_sql = "DROP TABLE %s" % escape(name) self.execute(drop_sql) def _create_sql_schema(self, frame, table_name, keys=None): diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index b185d530e056c..804d925790a6e 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -865,7 +865,7 @@ def test_uquery(self): def _get_sqlite_column_type(self, schema, column): for col in schema.split('\n'): - if col.split()[0].strip('[]') == column: + if col.split()[0].strip('""') == column: return col.split()[1] raise ValueError('Column %s not found' % (column)) @@ -1630,6 +1630,24 @@ def test_notnull_dtype(self): self.assertEqual(self._get_sqlite_column_type(tbl, 'Int'), 'INTEGER') self.assertEqual(self._get_sqlite_column_type(tbl, 'Float'), 'REAL') + def test_illegal_names(self): + # For sqlite, these should work fine + df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) + + # Raise error on blank + self.assertRaises(ValueError, df.to_sql, "", self.conn, + flavor=self.flavor) + + for ndx, weird_name in enumerate(['test_weird_name]','test_weird_name[', + 'test_weird_name`','test_weird_name"', 'test_weird_name\'']): + df.to_sql(weird_name, self.conn, flavor=self.flavor) + sql.table_exists(weird_name, self.conn) + + df2 = DataFrame([[1, 2], [3, 4]], columns=['a', weird_name]) + c_tbl = 'test_weird_col_name%d'%ndx + df.to_sql(c_tbl, self.conn, flavor=self.flavor) + sql.table_exists(c_tbl, self.conn) + class TestMySQLLegacy(TestSQLiteFallback): """ @@ -1721,6 +1739,19 @@ def test_to_sql_save_index(self): def test_to_sql_save_index(self): self._to_sql_save_index() + def test_illegal_names(self): + # For MySQL, these should raise ValueError + for ndx, illegal_name in enumerate(['test_illegal_name]','test_illegal_name[', + 'test_illegal_name`','test_illegal_name"', 'test_illegal_name\'', '']): + df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) + self.assertRaises(ValueError, df.to_sql, illegal_name, self.conn, + flavor=self.flavor, index=False) + + df2 = DataFrame([[1, 2], [3, 4]], columns=['a', illegal_name]) + c_tbl = 'test_illegal_col_name%d'%ndx + self.assertRaises(ValueError, df2.to_sql, 'test_illegal_col_name', + self.conn, flavor=self.flavor, index=False) + #------------------------------------------------------------------------------ #--- Old tests from 0.13.1 (before refactor using sqlalchemy) @@ -1817,7 +1848,7 @@ def test_schema(self): frame = tm.makeTimeDataFrame() create_sql = sql.get_schema(frame, 'test', 'sqlite', keys=['A', 'B'],) lines = create_sql.splitlines() - self.assertTrue('PRIMARY KEY ([A],[B])' in create_sql) + self.assertTrue('PRIMARY KEY ("A","B")' in create_sql) cur = self.db.cursor() cur.execute(create_sql)
Working with the SQL code, I realized that the legacy code does not properly validate / escape passed in table and column names. E.g.: ``` n [116]: import pandas as pd import pandas.io.sql as sql import sqlite3 df = pd.DataFrame({'a':[1,2],'b':[2,3]}) con = sqlite3.connect(':memory:') db = sql.SQLiteDatabase(con, 'sqlite') t=sql.SQLiteTable('a; DELETE FROM contacts; INSERT INTO b', db, frame=df) print t.insert_statement() ``` results in: ``` INSERT INTO a; DELETE FROM contacts; INSERT INTO b ([index],[a],[b]) VALUES (?,?,?) ``` This fixes the issues.
https://api.github.com/repos/pandas-dev/pandas/pulls/8986
2014-12-03T19:47:26Z
2015-01-26T00:04:28Z
2015-01-26T00:04:27Z
2015-01-26T00:04:38Z
BUG in read_csv skipping rows after a row with trailing spaces, #8983
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 740263bed7970..e86b53ef745d3 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -165,7 +165,7 @@ Bug Fixes of the level names are numbers (:issue:`8584`). - Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is not lexically sorted or unique (:issue:`7724`) -- BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) +- BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`), (:issue:`8983`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 59647b4c781e5..05a5493d0c70c 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -3049,17 +3049,17 @@ def test_comment_skiprows(self): tm.assert_almost_equal(df.values, expected) def test_trailing_spaces(self): - data = """skip + data = """A B C random line with trailing spaces skip 1,2,3 1,2.,4. random line with trailing tabs\t\t\t -5.,NaN,10.0 +5.1,NaN,10.0 """ expected = pd.DataFrame([[1., 2., 4.], - [5., np.nan, 10.]]) + [5.1, np.nan, 10.]]) # this should ignore six lines including lines with trailing # whitespace and blank lines. issues 8661, 8679 df = self.read_csv(StringIO(data.replace(',', ' ')), @@ -3070,6 +3070,13 @@ def test_trailing_spaces(self): header=None, delim_whitespace=True, skiprows=[0,1,2,3,5,6], skip_blank_lines=True) tm.assert_frame_equal(df, expected) + # test skipping set of rows after a row with trailing spaces, issue #8983 + expected = pd.DataFrame({"A":[1., 5.1], "B":[2., np.nan], + "C":[4., 10]}) + df = self.read_table(StringIO(data.replace(',', ' ')), + delim_whitespace=True, + skiprows=[1,2,3,5,6], skip_blank_lines=True) + tm.assert_frame_equal(df, expected) def test_comment_header(self): data = """# empty diff --git a/pandas/src/parser/tokenizer.c b/pandas/src/parser/tokenizer.c index fc96cc5429775..a64235c7c9732 100644 --- a/pandas/src/parser/tokenizer.c +++ b/pandas/src/parser/tokenizer.c @@ -1324,6 +1324,7 @@ int tokenize_whitespace(parser_t *self, size_t line_limit) if (c == '\n') { END_LINE(); self->state = START_RECORD; + break; } else if (c == '\r') { self->state = EAT_CRNL; break;
Update tokenizer.c to fix a BUG in read_csv skipping rows after tokenizing a row with trailing spaces, Closes #8983
https://api.github.com/repos/pandas-dev/pandas/pulls/8984
2014-12-03T18:18:24Z
2014-12-03T21:56:45Z
2014-12-03T21:56:45Z
2014-12-03T23:55:42Z
FIX: Workaround for integer hashing
diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 45d3274088c75..6ef8de26906db 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -611,9 +611,10 @@ class StataMissingValue(StringMixin): MISSING_VALUES = {} bases = (101, 32741, 2147483621) for b in bases: - MISSING_VALUES[b] = '.' + # Conversion to long to avoid hash issues on 32 bit platforms #8968 + MISSING_VALUES[compat.long(b)] = '.' for i in range(1, 27): - MISSING_VALUES[i + b] = '.' + chr(96 + i) + MISSING_VALUES[compat.long(i + b)] = '.' + chr(96 + i) float32_base = b'\x00\x00\x00\x7f' increment = struct.unpack('<i', b'\x00\x08\x00\x00')[0] @@ -643,6 +644,8 @@ class StataMissingValue(StringMixin): def __init__(self, value): self._value = value + # Conversion to long to avoid hash issues on 32 bit platforms #8968 + value = compat.long(value) if value < 2147483648 else float(value) self._str = self.MISSING_VALUES[value] string = property(lambda self: self._str, @@ -1375,13 +1378,6 @@ def _pad_bytes(name, length): return name + "\x00" * (length - len(name)) -def _default_names(nvar): - """ - Returns default Stata names v1, v2, ... vnvar - """ - return ["v%d" % i for i in range(1, nvar+1)] - - def _convert_datetime_to_stata_type(fmt): """ Converts from one of the stata date formats to a type in TYPE_MAP
Force conversion to integer for missing values when they must be integer to avoid hash errors on 32 bit platforms. closes #8968
https://api.github.com/repos/pandas-dev/pandas/pulls/8982
2014-12-03T12:40:22Z
2014-12-06T15:10:53Z
2014-12-06T15:10:53Z
2015-01-18T22:42:16Z
BUG: Bug in Timestamp-Timestamp not returning a Timedelta type (GH8865)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..bdfa858bfb2e5 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -92,6 +92,24 @@ Experimental Bug Fixes ~~~~~~~~~ + +- Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) +- Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) +- Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) +- Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) +- 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`) +- ``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`). +- ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) +- ``slice`` string method now takes step into account (:issue:`8754`) +- Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) +- Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) +- Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) + - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index a91c2573cc84e..615346f34b5bf 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -285,8 +285,8 @@ def test_ops(self): expected = pd.Period(ordinal=getattr(o.values, op)(), freq=o.freq) try: self.assertEqual(result, expected) - except ValueError: - # comparing tz-aware series with np.array results in ValueError + except TypeError: + # comparing tz-aware series with np.array results in TypeError expected = expected.astype('M8[ns]').astype('int64') self.assertEqual(result.value, expected) diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py index b523fb1d56290..b223d2bfd9ebc 100644 --- a/pandas/tseries/base.py +++ b/pandas/tseries/base.py @@ -346,7 +346,7 @@ def __sub__(self, other): cls.__sub__ = __sub__ def __rsub__(self, other): - return -self + other + return -(self - other) cls.__rsub__ = __rsub__ cls.__iadd__ = __add__ diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index e7c001ac57c0a..edb6d34f65f5e 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -381,7 +381,7 @@ def _generate(cls, start, end, periods, name, offset, try: inferred_tz = tools._infer_tzinfo(start, end) except: - raise ValueError('Start and end cannot both be tz-aware with ' + raise TypeError('Start and end cannot both be tz-aware with ' 'different timezones') inferred_tz = tslib.maybe_get_tz(inferred_tz) @@ -645,6 +645,11 @@ def _sub_datelike(self, other): from pandas import TimedeltaIndex other = Timestamp(other) + + # require tz compat + if tslib.get_timezone(self.tz) != tslib.get_timezone(other.tzinfo): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + i8 = self.asi8 result = i8 - other.value result = self._maybe_mask_results(result,fill_value=tslib.iNaT) diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py index 917e10c4b7706..d3393feb2ca33 100644 --- a/pandas/tseries/tests/test_base.py +++ b/pandas/tseries/tests/test_base.py @@ -468,6 +468,74 @@ def test_subtraction_ops(self): expected = DatetimeIndex(['20121231',pd.NaT,'20121230']) tm.assert_index_equal(result,expected) + def test_subtraction_ops_with_tz(self): + + # check that dt/dti subtraction ops with tz are validated + dti = date_range('20130101',periods=3) + ts = Timestamp('20130101') + dt = ts.to_datetime() + dti_tz = date_range('20130101',periods=3).tz_localize('US/Eastern') + ts_tz = Timestamp('20130101').tz_localize('US/Eastern') + ts_tz2 = Timestamp('20130101').tz_localize('CET') + dt_tz = ts_tz.to_datetime() + td = Timedelta('1 days') + + def _check(result, expected): + self.assertEqual(result,expected) + self.assertIsInstance(result, Timedelta) + + # scalars + result = ts - ts + expected = Timedelta('0 days') + _check(result, expected) + + result = dt_tz - ts_tz + expected = Timedelta('0 days') + _check(result, expected) + + result = ts_tz - dt_tz + expected = Timedelta('0 days') + _check(result, expected) + + # tz mismatches + self.assertRaises(TypeError, lambda : dt_tz - ts) + self.assertRaises(TypeError, lambda : dt_tz - dt) + self.assertRaises(TypeError, lambda : dt_tz - ts_tz2) + self.assertRaises(TypeError, lambda : dt - dt_tz) + self.assertRaises(TypeError, lambda : ts - dt_tz) + self.assertRaises(TypeError, lambda : ts_tz2 - ts) + self.assertRaises(TypeError, lambda : ts_tz2 - dt) + self.assertRaises(TypeError, lambda : ts_tz - ts_tz2) + + # with dti + self.assertRaises(TypeError, lambda : dti - ts_tz) + self.assertRaises(TypeError, lambda : dti_tz - ts) + self.assertRaises(TypeError, lambda : dti_tz - ts_tz2) + + result = dti_tz-dt_tz + expected = TimedeltaIndex(['0 days','1 days','2 days']) + tm.assert_index_equal(result,expected) + + result = dt_tz-dti_tz + expected = TimedeltaIndex(['0 days','-1 days','-2 days']) + tm.assert_index_equal(result,expected) + + result = dti_tz-ts_tz + expected = TimedeltaIndex(['0 days','1 days','2 days']) + tm.assert_index_equal(result,expected) + + result = ts_tz-dti_tz + expected = TimedeltaIndex(['0 days','-1 days','-2 days']) + tm.assert_index_equal(result,expected) + + result = td - td + expected = Timedelta('0 days') + _check(result, expected) + + result = dti_tz - td + expected = DatetimeIndex(['20121231','20130101','20130102'],tz='US/Eastern') + tm.assert_index_equal(result,expected) + def test_dti_tdi_numeric_ops(self): # These are normally union/diff set-like ops diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 6c358bd99e620..2e59febb2c62b 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -5,7 +5,7 @@ from pandas import tslib import datetime -from pandas.core.api import Timestamp, Series +from pandas.core.api import Timestamp, Series, Timedelta from pandas.tslib import period_asfreq, period_ordinal, get_timezone from pandas.tseries.index import date_range from pandas.tseries.frequencies import get_freq @@ -232,13 +232,13 @@ def test_tz(self): conv = local.tz_convert('US/Eastern') self.assertEqual(conv.nanosecond, 5) self.assertEqual(conv.hour, 19) - + def test_tz_localize_ambiguous(self): - + ts = Timestamp('2014-11-02 01:00') ts_dst = ts.tz_localize('US/Eastern', ambiguous=True) ts_no_dst = ts.tz_localize('US/Eastern', ambiguous=False) - + rng = date_range('2014-11-02', periods=3, freq='H', tz='US/Eastern') self.assertEqual(rng[1], ts_dst) self.assertEqual(rng[2], ts_no_dst) @@ -679,8 +679,8 @@ def test_addition_subtraction_types(self): self.assertEqual(type(timestamp_instance - 1), Timestamp) # Timestamp + datetime not supported, though subtraction is supported and yields timedelta - self.assertEqual(type(timestamp_instance - datetime_instance), datetime.timedelta) - + # more tests in tseries/base/tests/test_base.py + self.assertEqual(type(timestamp_instance - datetime_instance), Timedelta) self.assertEqual(type(timestamp_instance + timedelta_instance), Timestamp) self.assertEqual(type(timestamp_instance - timedelta_instance), Timestamp) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 8efc174d6890b..30245d4de2f8d 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -810,10 +810,10 @@ cdef class _Timestamp(datetime): object other) except -1: if self.tzinfo is None: if other.tzinfo is not None: - raise ValueError('Cannot compare tz-naive and tz-aware ' + raise TypeError('Cannot compare tz-naive and tz-aware ' 'timestamps') elif other.tzinfo is None: - raise ValueError('Cannot compare tz-naive and tz-aware timestamps') + raise TypeError('Cannot compare tz-naive and tz-aware timestamps') cpdef datetime to_datetime(_Timestamp self): cdef: @@ -863,6 +863,11 @@ cdef class _Timestamp(datetime): # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex elif getattr(other,'_typ',None) == 'datetimeindex': + + # we may be passed reverse ops + if get_timezone(getattr(self,'tzinfo',None)) != get_timezone(other.tz): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + return -other.__sub__(self) # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex @@ -871,6 +876,23 @@ cdef class _Timestamp(datetime): elif other is NaT: return NaT + + # coerce if necessary if we are a Timestamp-like + if isinstance(self, datetime) and (isinstance(other, datetime) or is_datetime64_object(other)): + self = Timestamp(self) + other = Timestamp(other) + + # validate tz's + if get_timezone(self.tzinfo) != get_timezone(other.tzinfo): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + + # scalar Timestamp/datetime - Timestamp/datetime -> yields a Timedelta + try: + return Timedelta(self.value-other.value) + except (OverflowError, OutOfBoundsDatetime): + pass + + # scalar Timestamp/datetime - Timedelta -> yields a Timestamp (with same timezone if specified) return datetime.__sub__(self, other) cpdef _get_field(self, field):
closes #8865
https://api.github.com/repos/pandas-dev/pandas/pulls/8981
2014-12-03T12:40:22Z
2014-12-04T02:48:19Z
2014-12-04T02:48:19Z
2014-12-04T02:48:20Z
TST/COMPAT: tests and compat for unicode for lib.max_len_string_array
diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 82408cd460fcd..2a5b93d111acc 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -898,17 +898,17 @@ def clean_index_list(list obj): @cython.boundscheck(False) @cython.wraparound(False) -def max_len_string_array(ndarray[object, ndim=1] arr): +def max_len_string_array(ndarray arr): """ return the maximum size of elements in a 1-dim string array """ cdef: int i, m, l - length = arr.shape[0] + int length = arr.shape[0] object v m = 0 for i from 0 <= i < length: v = arr[i] - if PyString_Check(v) or PyBytes_Check(v): + if PyString_Check(v) or PyBytes_Check(v) or PyUnicode_Check(v): l = len(v) if l > m: diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 2873cd81d4744..1276a7fc96a46 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -3,10 +3,21 @@ import numpy as np import pandas as pd -from pandas.lib import isscalar, item_from_zerodim +from pandas.lib import isscalar, item_from_zerodim, max_len_string_array import pandas.util.testing as tm from pandas.compat import u +class TestMisc(tm.TestCase): + + def test_max_len_string_array(self): + + arr = np.array(['foo','b',np.nan],dtype='object') + self.assertTrue(max_len_string_array(arr),3) + + # unicode + arr = arr.astype('U') + self.assertTrue(max_len_string_array(arr),3) + class TestIsscalar(tm.TestCase): def test_isscalar_builtin_scalars(self): self.assertTrue(isscalar(None))
https://api.github.com/repos/pandas-dev/pandas/pulls/8978
2014-12-03T03:26:28Z
2014-12-03T07:04:47Z
2014-12-03T07:04:47Z
2014-12-03T07:04:47Z
BUG: StataWriter uses incorrect string length
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 929471acb3105..aca1320980720 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -166,3 +166,10 @@ Bug Fixes not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) + + + + + +- Bug in `StataWriter` the produces writes strings with 244 characters irrespective of actual size (:issue:`8969`) + diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 45d3274088c75..cd37efd8e0991 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1409,7 +1409,7 @@ def _maybe_convert_to_int_keys(convert_dates, varlist): return new_dict -def _dtype_to_stata_type(dtype): +def _dtype_to_stata_type(dtype, column): """ Converts dtype types to stata types. Returns the byte of the given ordinal. See TYPE_MAP and comments for an explanation. This is also explained in @@ -1425,13 +1425,14 @@ def _dtype_to_stata_type(dtype): If there are dates to convert, then dtype will already have the correct type inserted. """ - #TODO: expand to handle datetime to integer conversion + # TODO: expand to handle datetime to integer conversion if dtype.type == np.string_: return chr(dtype.itemsize) elif dtype.type == np.object_: # try to coerce it to the biggest string # not memory efficient, what else could we # do? - return chr(244) + itemsize = max_len_string_array(column.values) + return chr(max(itemsize, 1)) elif dtype == np.float64: return chr(255) elif dtype == np.float32: @@ -1461,6 +1462,7 @@ def _dtype_to_default_stata_fmt(dtype, column): int16 -> "%8.0g" int8 -> "%8.0g" """ + # TODO: Refactor to combine type with format # TODO: expand this to handle a default datetime format? if dtype.type == np.object_: inferred_dtype = infer_dtype(column.dropna()) @@ -1470,8 +1472,7 @@ def _dtype_to_default_stata_fmt(dtype, column): itemsize = max_len_string_array(column.values) if itemsize > 244: raise ValueError(excessive_string_length_error % column.name) - - return "%" + str(itemsize) + "s" + return "%" + str(max(itemsize, 1)) + "s" elif dtype == np.float64: return "%10.0g" elif dtype == np.float32: @@ -1718,10 +1719,11 @@ def _prepare_pandas(self, data): self._convert_dates[key] ) dtypes[key] = np.dtype(new_type) - self.typlist = [_dtype_to_stata_type(dt) for dt in dtypes] + self.typlist = [] self.fmtlist = [] for col, dtype in dtypes.iteritems(): self.fmtlist.append(_dtype_to_default_stata_fmt(dtype, data[col])) + self.typlist.append(_dtype_to_stata_type(dtype, data[col])) # set the given format for the datetime cols if self._convert_dates is not None: diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index a99bcf741792f..6a3c16655745e 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -593,10 +593,12 @@ def test_minimal_size_col(self): with tm.ensure_clean() as path: original.to_stata(path, write_index=False) sr = StataReader(path) + typlist = sr.typlist variables = sr.varlist formats = sr.fmtlist - for variable, fmt in zip(variables, formats): + for variable, fmt, typ in zip(variables, formats, typlist): self.assertTrue(int(variable[1:]) == int(fmt[1:-1])) + self.assertTrue(int(variable[1:]) == typ) def test_excessively_long_string(self): str_lens = (1, 244, 500) @@ -850,7 +852,6 @@ def test_categorical_order(self): # Check identity of codes for col in expected: if is_categorical_dtype(expected[col]): - print(col) tm.assert_series_equal(expected[col].cat.codes, parsed_115[col].cat.codes) tm.assert_index_equal(expected[col].cat.categories, diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 82408cd460fcd..2a5b93d111acc 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -898,17 +898,17 @@ def clean_index_list(list obj): @cython.boundscheck(False) @cython.wraparound(False) -def max_len_string_array(ndarray[object, ndim=1] arr): +def max_len_string_array(ndarray arr): """ return the maximum size of elements in a 1-dim string array """ cdef: int i, m, l - length = arr.shape[0] + int length = arr.shape[0] object v m = 0 for i from 0 <= i < length: v = arr[i] - if PyString_Check(v) or PyBytes_Check(v): + if PyString_Check(v) or PyBytes_Check(v) or PyUnicode_Check(v): l = len(v) if l > m:
Fixes bug where StataWriter always writes strings with a size of 244. closes #8969
https://api.github.com/repos/pandas-dev/pandas/pulls/8977
2014-12-03T03:07:24Z
2014-12-03T14:24:58Z
2014-12-03T14:24:58Z
2015-01-18T22:42:19Z
COMPAT: infer_dtype not handling categoricals (GH8974)
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index e754f3c21de3c..dbe6f2f1f8351 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -21,6 +21,8 @@ def is_period(object val): return util.is_period_object(val) _TYPE_MAP = { + 'categorical' : 'categorical', + 'category' : 'categorical', 'int8': 'integer', 'int16': 'integer', 'int32': 'integer', @@ -65,7 +67,23 @@ try: except AttributeError: pass +cdef _try_infer_map(v): + """ if its in our map, just return the dtype """ + cdef: + object val_name, val_kind + val_name = v.dtype.name + if val_name in _TYPE_MAP: + return _TYPE_MAP[val_name] + val_kind = v.dtype.kind + if val_kind in _TYPE_MAP: + return _TYPE_MAP[val_kind] + return None + def infer_dtype(object _values): + """ + we are coercing to an ndarray here + """ + cdef: Py_ssize_t i, n object val @@ -73,21 +91,29 @@ def infer_dtype(object _values): if isinstance(_values, np.ndarray): values = _values - elif hasattr(_values,'values'): - values = _values.values + elif hasattr(_values,'dtype'): + + # this will handle ndarray-like + # e.g. categoricals + try: + values = getattr(_values, 'values', _values) + except: + val = _try_infer_map(_values) + if val is not None: + return val + + # its ndarray like but we can't handle + raise ValueError("cannot infer type for {0}".format(type(_values))) + else: if not isinstance(_values, list): _values = list(_values) values = list_to_object_array(_values) values = getattr(values, 'values', values) - - val_name = values.dtype.name - if val_name in _TYPE_MAP: - return _TYPE_MAP[val_name] - val_kind = values.dtype.kind - if val_kind in _TYPE_MAP: - return _TYPE_MAP[val_kind] + val = _try_infer_map(values) + if val is not None: + return val if values.dtype != np.object_: values = values.astype('O') diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 5c26fce2b111e..04092346a70e8 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -660,6 +660,24 @@ def test_object(self): result = lib.infer_dtype(arr) self.assertEqual(result, 'mixed') + def test_categorical(self): + + # GH 8974 + from pandas import Categorical, Series + arr = Categorical(list('abc')) + result = lib.infer_dtype(arr) + self.assertEqual(result, 'categorical') + + result = lib.infer_dtype(Series(arr)) + self.assertEqual(result, 'categorical') + + arr = Categorical(list('abc'),categories=['cegfab'],ordered=True) + result = lib.infer_dtype(arr) + self.assertEqual(result, 'categorical') + + result = lib.infer_dtype(Series(arr)) + self.assertEqual(result, 'categorical') + class TestMoments(tm.TestCase): pass
closes #8974
https://api.github.com/repos/pandas-dev/pandas/pulls/8975
2014-12-03T02:14:19Z
2014-12-03T02:53:18Z
2014-12-03T02:53:18Z
2014-12-03T02:53:18Z
ENH: Infer dtype from non-nulls when pushing to SQL
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a329cb25173cf..8c2fbc059ce5b 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -115,6 +115,7 @@ Enhancements - ``to_datetime`` gains an ``exact`` keyword to allow for a format to not require an exact match for a provided format string (if its ``False). ``exact`` defaults to ``True`` (meaning that exact matching is still the default) (:issue:`8904`) - Added ``axvlines`` boolean option to parallel_coordinates plot function, determines whether vertical lines will be printed, default is True - Added ability to read table footers to read_html (:issue:`8552`) +- ``to_sql`` now infers datatypes of non-NA values for columns that contain NA values and have dtype ``object`` (:issue:`8778`). .. _whatsnew_0152.performance: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 77527f867fad8..a1b3180e721fc 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -885,37 +885,56 @@ def _harmonize_columns(self, parse_dates=None): except KeyError: pass # this column not in results + def _get_notnull_col_dtype(self, col): + """ + Infer datatype of the Series col. In case the dtype of col is 'object' + and it contains NA values, this infers the datatype of the not-NA + values. Needed for inserting typed data containing NULLs, GH8778. + """ + col_for_inference = col + if col.dtype == 'object': + notnulldata = col[~isnull(col)] + if len(notnulldata): + col_for_inference = notnulldata + + return lib.infer_dtype(col_for_inference) + def _sqlalchemy_type(self, col): - from sqlalchemy.types import (BigInteger, Float, Text, Boolean, - DateTime, Date, Time) dtype = self.dtype or {} if col.name in dtype: return self.dtype[col.name] - if com.is_datetime64_dtype(col): + col_type = self._get_notnull_col_dtype(col) + + from sqlalchemy.types import (BigInteger, Float, Text, Boolean, + DateTime, Date, Time) + + if col_type == 'datetime64': try: tz = col.tzinfo return DateTime(timezone=True) except: return DateTime - if com.is_timedelta64_dtype(col): + if col_type == 'timedelta64': warnings.warn("the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the " "database.", UserWarning) return BigInteger - elif com.is_float_dtype(col): + elif col_type == 'floating': return Float - elif com.is_integer_dtype(col): + elif col_type == 'integer': # TODO: Refine integer size. return BigInteger - elif com.is_bool_dtype(col): + elif col_type == 'boolean': return Boolean - inferred = lib.infer_dtype(com._ensure_object(col)) - if inferred == 'date': + elif col_type == 'date': return Date - if inferred == 'time': + elif col_type == 'time': return Time + elif col_type == 'complex': + raise ValueError('Complex datatypes not supported') + return Text def _numpy_type(self, sqltype): @@ -1187,15 +1206,15 @@ def _create_sql_schema(self, frame, table_name, keys=None): # SQLAlchemy installed # SQL type convertions for each DB _SQL_TYPES = { - 'text': { + 'string': { 'mysql': 'VARCHAR (63)', 'sqlite': 'TEXT', }, - 'float': { + 'floating': { 'mysql': 'FLOAT', 'sqlite': 'REAL', }, - 'int': { + 'integer': { 'mysql': 'BIGINT', 'sqlite': 'INTEGER', }, @@ -1211,12 +1230,13 @@ def _create_sql_schema(self, frame, table_name, keys=None): 'mysql': 'TIME', 'sqlite': 'TIME', }, - 'bool': { + 'boolean': { 'mysql': 'BOOLEAN', 'sqlite': 'INTEGER', } } + # SQL enquote and wildcard symbols _SQL_SYMB = { 'mysql': { @@ -1291,8 +1311,8 @@ def _create_table_setup(self): br_l = _SQL_SYMB[flv]['br_l'] # left val quote char br_r = _SQL_SYMB[flv]['br_r'] # right val quote char - create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, ctype) - for cname, ctype, _ in column_names_and_types] + create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, col_type) + for cname, col_type, _ in column_names_and_types] if self.keys is not None and len(self.keys): cnames_br = ",".join([br_l + c + br_r for c in self.keys]) create_tbl_stmts.append( @@ -1317,30 +1337,27 @@ def _sql_type_name(self, col): dtype = self.dtype or {} if col.name in dtype: return dtype[col.name] - pytype = col.dtype.type - pytype_name = "text" - if issubclass(pytype, np.floating): - pytype_name = "float" - elif com.is_timedelta64_dtype(pytype): + + col_type = self._get_notnull_col_dtype(col) + if col_type == 'timedelta64': warnings.warn("the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the " "database.", UserWarning) - pytype_name = "int" - elif issubclass(pytype, np.integer): - pytype_name = "int" - elif issubclass(pytype, np.datetime64) or pytype is datetime: - # Caution: np.datetime64 is also a subclass of np.number. - pytype_name = "datetime" - elif issubclass(pytype, np.bool_): - pytype_name = "bool" - elif issubclass(pytype, np.object): - pytype = lib.infer_dtype(com._ensure_object(col)) - if pytype == "date": - pytype_name = "date" - elif pytype == "time": - pytype_name = "time" - - return _SQL_TYPES[pytype_name][self.pd_sql.flavor] + col_type = "integer" + + elif col_type == "datetime64": + col_type = "datetime" + + elif col_type == "empty": + col_type = "string" + + elif col_type == "complex": + raise ValueError('Complex datatypes not supported') + + if col_type not in _SQL_TYPES: + col_type = "string" + + return _SQL_TYPES[col_type][self.pd_sql.flavor] class SQLiteDatabase(PandasSQL): diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index eb46df7686d18..c7b6b77ae7aea 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -560,6 +560,11 @@ def test_timedelta(self): result = sql.read_sql_query('SELECT * FROM test_timedelta', self.conn) tm.assert_series_equal(result['foo'], df['foo'].astype('int64')) + def test_complex(self): + df = DataFrame({'a':[1+1j, 2j]}) + # Complex data type should raise error + self.assertRaises(ValueError, df.to_sql, 'test_complex', self.conn) + def test_to_sql_index_label(self): temp_frame = DataFrame({'col1': range(4)}) @@ -1175,19 +1180,38 @@ def test_dtype(self): (0.9, None)] df = DataFrame(data, columns=cols) df.to_sql('dtype_test', self.conn) - df.to_sql('dtype_test2', self.conn, dtype={'B': sqlalchemy.Boolean}) + df.to_sql('dtype_test2', self.conn, dtype={'B': sqlalchemy.TEXT}) + meta = sqlalchemy.schema.MetaData(bind=self.conn) + meta.reflect() + sqltype = meta.tables['dtype_test2'].columns['B'].type + self.assertTrue(isinstance(sqltype, sqlalchemy.TEXT)) + self.assertRaises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': str}) + + def test_notnull_dtype(self): + cols = {'Bool': Series([True,None]), + 'Date': Series([datetime(2012, 5, 1), None]), + 'Int' : Series([1, None], dtype='object'), + 'Float': Series([1.1, None]) + } + df = DataFrame(cols) + + tbl = 'notnull_dtype_test' + df.to_sql(tbl, self.conn) + returned_df = sql.read_sql_table(tbl, self.conn) meta = sqlalchemy.schema.MetaData(bind=self.conn) meta.reflect() - self.assertTrue(isinstance(meta.tables['dtype_test'].columns['B'].type, - sqltypes.TEXT)) if self.flavor == 'mysql': my_type = sqltypes.Integer else: my_type = sqltypes.Boolean - self.assertTrue(isinstance(meta.tables['dtype_test2'].columns['B'].type, - my_type)) - self.assertRaises(ValueError, df.to_sql, - 'error', self.conn, dtype={'B': bool}) + + col_dict = meta.tables[tbl].columns + + self.assertTrue(isinstance(col_dict['Bool'].type, my_type)) + self.assertTrue(isinstance(col_dict['Date'].type, sqltypes.DateTime)) + self.assertTrue(isinstance(col_dict['Int'].type, sqltypes.Integer)) + self.assertTrue(isinstance(col_dict['Float'].type, sqltypes.Float)) class TestSQLiteAlchemy(_TestSQLAlchemy): @@ -1507,6 +1531,13 @@ def test_to_sql_save_index(self): def test_transactions(self): self._transaction_test() + def _get_sqlite_column_type(self, table, column): + recs = self.conn.execute('PRAGMA table_info(%s)' % table) + for cid, name, ctype, not_null, default, pk in recs: + if name == column: + return ctype + raise ValueError('Table %s, column %s not found' % (table, column)) + def test_dtype(self): if self.flavor == 'mysql': raise nose.SkipTest('Not applicable to MySQL legacy') @@ -1515,20 +1546,35 @@ def test_dtype(self): (0.9, None)] df = DataFrame(data, columns=cols) df.to_sql('dtype_test', self.conn) - df.to_sql('dtype_test2', self.conn, dtype={'B': 'bool'}) + df.to_sql('dtype_test2', self.conn, dtype={'B': 'STRING'}) - def get_column_type(table, column): - recs = self.conn.execute('PRAGMA table_info(%s)' % table) - for cid, name, ctype, not_null, default, pk in recs: - if name == column: - return ctype - raise ValueError('Table %s, column %s not found' % (table, column)) - - self.assertEqual(get_column_type('dtype_test', 'B'), 'TEXT') - self.assertEqual(get_column_type('dtype_test2', 'B'), 'bool') + # sqlite stores Boolean values as INTEGER + self.assertEqual(self._get_sqlite_column_type('dtype_test', 'B'), 'INTEGER') + + self.assertEqual(self._get_sqlite_column_type('dtype_test2', 'B'), 'STRING') self.assertRaises(ValueError, df.to_sql, 'error', self.conn, dtype={'B': bool}) + def test_notnull_dtype(self): + if self.flavor == 'mysql': + raise nose.SkipTest('Not applicable to MySQL legacy') + + cols = {'Bool': Series([True,None]), + 'Date': Series([datetime(2012, 5, 1), None]), + 'Int' : Series([1, None], dtype='object'), + 'Float': Series([1.1, None]) + } + df = DataFrame(cols) + + tbl = 'notnull_dtype_test' + df.to_sql(tbl, self.conn) + + self.assertEqual(self._get_sqlite_column_type(tbl, 'Bool'), 'INTEGER') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Date'), 'TIMESTAMP') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Int'), 'INTEGER') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Float'), 'REAL') + + class TestMySQLLegacy(TestSQLiteFallback): """ Test the legacy mode against a MySQL database.
Closes #8778 This infers dtype from non-null values for insertion into SQL database. See #8778 . I had to alter @tiagoantao test a bit. Like @tiagoantao, I skipped writing tests for legacy MySQL. Support for this will be removed soon, right? As a side note, `lib.infer_dtype` throws an exception for categorical data -- probably shouldn't happen, right? @jorisvandenbossche @jahfet @tiagoantao
https://api.github.com/repos/pandas-dev/pandas/pulls/8973
2014-12-03T01:21:26Z
2014-12-08T07:42:33Z
2014-12-08T07:42:33Z
2014-12-08T07:42:42Z
BUG: ValueError raised by cummin/cummax when datetime64 Series contains NaT.
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 929471acb3105..0a0bed826abba 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -166,3 +166,4 @@ Bug Fixes not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) +- Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 52f37ee24f69a..b948ceb9b6b88 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4112,13 +4112,17 @@ def func(self, axis=None, dtype=None, out=None, skipna=True, axis = self._get_axis_number(axis) y = _values_from_object(self).copy() - if not issubclass(y.dtype.type, (np.integer, np.bool_)): + + if skipna and issubclass(y.dtype.type, + (np.datetime64, np.timedelta64)): + result = accum_func(y, axis) + mask = isnull(self) + np.putmask(result, mask, pd.tslib.iNaT) + elif skipna and not issubclass(y.dtype.type, (np.integer, np.bool_)): mask = isnull(self) - if skipna: - np.putmask(y, mask, mask_a) + np.putmask(y, mask, mask_a) result = accum_func(y, axis) - if skipna: - np.putmask(result, mask, mask_b) + np.putmask(result, mask, mask_b) else: result = accum_func(y, axis) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c4c2eebacb0e9..df48c5e62a9b6 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2309,6 +2309,62 @@ def test_cummax(self): self.assert_numpy_array_equal(result, expected) + def test_cummin_datetime64(self): + s = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-1'])) + result = s.cummin(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1', '2000-1-1'])) + result = s.cummin(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummax_datetime64(self): + s = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-2', 'NaT', '2000-1-3'])) + result = s.cummax(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-3'])) + result = s.cummax(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummin_timedelta64(self): + s = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '1 min', ])) + result = s.cummin(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', '2 min', '1 min', '1 min', '1 min', ])) + result = s.cummin(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummax_timedelta64(self): + s = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '2 min', 'NaT', '3 min', ])) + result = s.cummax(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', '2 min', '2 min', '2 min', '3 min', ])) + result = s.cummax(skipna=False) + self.assert_series_equal(expected, result) + def test_npdiff(self): raise nose.SkipTest("skipping due to Series no longer being an " "ndarray")
closes #8965
https://api.github.com/repos/pandas-dev/pandas/pulls/8966
2014-12-02T13:00:45Z
2014-12-03T14:27:36Z
2014-12-03T14:27:36Z
2014-12-03T14:27:45Z
Fixes #8933 simple renaming
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 7dfdc88dddbff..5b3e9e8a22b12 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -18,7 +18,7 @@ from pandas.core.common import (CategoricalDtype, ABCSeries, isnull, notnull, is_categorical_dtype, is_integer_dtype, is_object_dtype, _possibly_infer_to_datetimelike, get_dtype_kinds, - is_list_like, _is_sequence, + is_list_like, is_sequence, _ensure_platform_int, _ensure_object, _ensure_int64, _coerce_indexer_dtype, _values_from_object, take_1d) from pandas.util.terminal import get_terminal_size @@ -1477,7 +1477,7 @@ def _convert_to_list_like(list_like): return list_like if isinstance(list_like, list): return list_like - if (_is_sequence(list_like) or isinstance(list_like, tuple) + if (is_sequence(list_like) or isinstance(list_like, tuple) or isinstance(list_like, types.GeneratorType)): return list(list_like) elif np.isscalar(list_like): diff --git a/pandas/core/common.py b/pandas/core/common.py index 6aff67412d677..f7f944bb418e9 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2504,7 +2504,7 @@ def is_list_like(arg): not isinstance(arg, compat.string_and_binary_types)) -def _is_sequence(x): +def is_sequence(x): try: iter(x) len(x) # it has a length @@ -2512,6 +2512,7 @@ def _is_sequence(x): except (TypeError, AttributeError): return False + def _get_callable_name(obj): # typical case has name if hasattr(obj, '__name__'): @@ -3093,7 +3094,7 @@ def as_escaped_unicode(thing, escape_chars=escape_chars): elif (isinstance(thing, dict) and _nest_lvl < get_option("display.pprint_nest_depth")): result = _pprint_dict(thing, _nest_lvl, quote_strings=True) - elif _is_sequence(thing) and _nest_lvl < \ + elif is_sequence(thing) and _nest_lvl < \ get_option("display.pprint_nest_depth"): result = _pprint_seq(thing, _nest_lvl, escape_chars=escape_chars, quote_strings=quote_strings) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a464b687209cb..7c7872cf7b6a5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -24,7 +24,7 @@ import numpy.ma as ma from pandas.core.common import (isnull, notnull, PandasError, _try_sort, - _default_index, _maybe_upcast, _is_sequence, + _default_index, _maybe_upcast, is_sequence, _infer_dtype_from_scalar, _values_from_object, is_list_like, _get_dtype, _maybe_box_datetimelike, is_categorical_dtype) @@ -2255,7 +2255,7 @@ def reindexer(value): elif isinstance(value, Categorical): value = value.copy() - elif (isinstance(value, Index) or _is_sequence(value)): + elif (isinstance(value, Index) or is_sequence(value)): from pandas.core.series import _sanitize_index value = _sanitize_index(value, self.index, copy=False) if not isinstance(value, (np.ndarray, Index)): @@ -2844,7 +2844,7 @@ def sort_index(self, axis=0, by=None, ascending=True, inplace=False, '(rows)') if not isinstance(by, list): by = [by] - if com._is_sequence(ascending) and len(by) != len(ascending): + if com.is_sequence(ascending) and len(by) != len(ascending): raise ValueError('Length of ascending (%d) != length of by' ' (%d)' % (len(ascending), len(by))) if len(by) > 1: @@ -3694,7 +3694,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True): com.pprint_thing(k),) raise - if len(results) > 0 and _is_sequence(results[0]): + if len(results) > 0 and is_sequence(results[0]): if not isinstance(results[0], Series): index = res_columns else: diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 048e4af20d02f..c9322a9371309 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -541,7 +541,7 @@ def _align_series(self, indexer, ser): # we have a frame, with multiple indexers on both axes; and a # series, so need to broadcast (see GH5206) if (sum_aligners == self.ndim and - all([com._is_sequence(_) for _ in indexer])): + all([com.is_sequence(_) for _ in indexer])): ser = ser.reindex(obj.axes[0][indexer[0]], copy=True).values # single indexer @@ -555,7 +555,7 @@ def _align_series(self, indexer, ser): ax = obj.axes[i] # multiple aligners (or null slices) - if com._is_sequence(idx) or isinstance(idx, slice): + if com.is_sequence(idx) or isinstance(idx, slice): if single_aligner and _is_null_slice(idx): continue new_ix = ax[idx] @@ -625,7 +625,7 @@ def _align_frame(self, indexer, df): sindexers = [] for i, ix in enumerate(indexer): ax = self.obj.axes[i] - if com._is_sequence(ix) or isinstance(ix, slice): + if com.is_sequence(ix) or isinstance(ix, slice): if idx is None: idx = ax[ix].ravel() elif cols is None: diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 0d13b6513b377..9465247056e27 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -25,7 +25,7 @@ def test_mut_exclusive(): def test_is_sequence(): - is_seq = com._is_sequence + is_seq = com.is_sequence assert(is_seq((1, 2))) assert(is_seq([1, 2])) assert(not is_seq("abcd")) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 4acf4d63d9de7..6a71160a08ae9 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -24,7 +24,7 @@ from numpy.testing import assert_array_equal import pandas as pd -from pandas.core.common import _is_sequence, array_equivalent, is_list_like +from pandas.core.common import is_sequence, array_equivalent, is_list_like import pandas.core.index as index import pandas.core.series as series import pandas.core.frame as frame @@ -945,7 +945,7 @@ def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None, if ndupe_l is None: ndupe_l = [1] * nlevels - assert (_is_sequence(ndupe_l) and len(ndupe_l) <= nlevels) + assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels) assert (names is None or names is False or names is True or len(names) is nlevels) assert idx_type is None or \
closes #8933 Refactored _is_sequence to is_sequence
https://api.github.com/repos/pandas-dev/pandas/pulls/8959
2014-12-02T09:00:48Z
2014-12-02T10:52:26Z
2014-12-02T10:52:26Z
2014-12-02T10:52:26Z
ENH: add contextmanager to HDFStore (#8791)
diff --git a/doc/source/io.rst b/doc/source/io.rst index ba19173546cb2..f2d5924edac77 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2348,7 +2348,7 @@ Closing a Store, Context Manager # Working with, and automatically closing the store with the context # manager - with get_store('store.h5') as store: + with HDFStore('store.h5') as store: store.keys() .. ipython:: python diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..57534fa2e1ef0 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -75,6 +75,7 @@ Enhancements - Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). - Added ``gbq.generate_bq_schema`` function to the gbq module (:issue:`8325`). - ``Series`` now works with map objects the same way as generators (:issue:`8909`). +- Added context manager to ``HDFStore`` (:issue:`8791`). Now with HDFStore('path') as store: should also close to store. get_store will be deprecated in the future. .. _whatsnew_0152.performance: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 56c444095ca51..05510f655f7be 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -251,33 +251,6 @@ def _tables(): return _table_mod -@contextmanager -def get_store(path, **kwargs): - """ - Creates an HDFStore instance. This function can be used in a with statement - - Parameters - ---------- - same as HDFStore - - Examples - -------- - >>> from pandas import DataFrame - >>> from numpy.random import randn - >>> bar = DataFrame(randn(10, 4)) - >>> with get_store('test.h5') as store: - ... store['foo'] = bar # write to HDF5 - ... bar = store['foo'] # retrieve - """ - store = None - try: - store = HDFStore(path, **kwargs) - yield store - finally: - if store is not None: - store.close() - - # interface to/from ### def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, @@ -289,7 +262,7 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, f = lambda store: store.put(key, value, **kwargs) if isinstance(path_or_buf, string_types): - with get_store(path_or_buf, mode=mode, complevel=complevel, + with HDFStore(path_or_buf, mode=mode, complevel=complevel, complib=complib) as store: f(store) else: @@ -493,6 +466,12 @@ def __unicode__(self): return output + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def keys(self): """ Return a (potentially unordered) list of the keys corresponding to the @@ -1288,6 +1267,12 @@ def _read_group(self, group, **kwargs): return s.read(**kwargs) +def get_store(path, **kwargs): + """ Backwards compatible alias for ``HDFStore`` + """ + return HDFStore(path, **kwargs) + + class TableIterator(object): """ define the iteration interface on a table diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index e2a99076e7607..e95d46f66f17f 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -172,6 +172,25 @@ def test_factory_fun(self): finally: safe_remove(self.path) + def test_context(self): + try: + with HDFStore(self.path) as tbl: + raise ValueError('blah') + except ValueError: + pass + finally: + safe_remove(self.path) + + try: + with HDFStore(self.path) as tbl: + tbl['a'] = tm.makeDataFrame() + + with HDFStore(self.path) as tbl: + self.assertEqual(len(tbl), 1) + self.assertEqual(type(tbl['a']), DataFrame) + finally: + safe_remove(self.path) + def test_conv_read_write(self): try: @@ -334,10 +353,10 @@ def test_api_default_format(self): pandas.set_option('io.hdf.default_format','table') df.to_hdf(path,'df3') - with get_store(path) as store: + with HDFStore(path) as store: self.assertTrue(store.get_storer('df3').is_table) df.to_hdf(path,'df4',append=True) - with get_store(path) as store: + with HDFStore(path) as store: self.assertTrue(store.get_storer('df4').is_table) pandas.set_option('io.hdf.default_format',None) @@ -463,11 +482,11 @@ def check(mode): # context if mode in ['r','r+']: def f(): - with get_store(path,mode=mode) as store: + with HDFStore(path,mode=mode) as store: pass self.assertRaises(IOError, f) else: - with get_store(path,mode=mode) as store: + with HDFStore(path,mode=mode) as store: self.assertEqual(store._handle.mode, mode) with ensure_clean_path(self.path) as path:
Added a context manager to HDFStore closes #8791
https://api.github.com/repos/pandas-dev/pandas/pulls/8958
2014-12-02T08:59:57Z
2014-12-04T11:30:36Z
2014-12-04T11:30:36Z
2014-12-04T11:30:51Z
BLD/TST: skip mpl 1.2.1 tests (GH8947)
diff --git a/.travis.yml b/.travis.yml index ea1a0d9d6752a..bf6a3f166e706 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,6 +38,13 @@ matrix: - BUILD_TYPE=conda - JOB_NAME: "27_nslow" - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests + - python: 2.7 + env: + - NOSE_ARGS="slow and not network and not disabled" + - FULL_DEPS=true + - JOB_TAG=_SLOW + - BUILD_TYPE=conda + - JOB_NAME: "27_slow" - python: 3.3 env: - NOSE_ARGS="not slow and not disabled" @@ -76,6 +83,13 @@ matrix: - CLIPBOARD_GUI=qt4 - BUILD_TYPE=pydata - JOB_NAME: "32_nslow" + - python: 2.7 + env: + - NOSE_ARGS="slow and not network and not disabled" + - FULL_DEPS=true + - JOB_TAG=_SLOW + - BUILD_TYPE=conda + - JOB_NAME: "27_slow" - python: 2.7 env: - EXPERIMENTAL=true diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt index 036e597e5b788..6c70bfd77ff3f 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.txt @@ -7,7 +7,7 @@ xlrd=0.9.2 numpy=1.7.1 cython=0.19.1 bottleneck=0.8.0 -matplotlib=1.3.0 +matplotlib=1.2.1 patsy=0.1.0 sqlalchemy=0.8.1 html5lib=1.0b2 diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.txt new file mode 100644 index 0000000000000..a1ecbceda40dd --- /dev/null +++ b/ci/requirements-2.7_SLOW.txt @@ -0,0 +1,25 @@ +dateutil +pytz +numpy +cython +matplotlib +scipy +patsy +statsmodels +xlwt +openpyxl +xlsxwriter +xlrd +numexpr +pytables +sqlalchemy +lxml +boto +bottleneck +psycopg2 +pymysql +html5lib +beautiful-soup +httplib2 +python-gflags +google-api-python-client diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 74ec6d22ca4cd..06902dded0da4 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -77,6 +77,9 @@ def setUp(self): else: self.bp_n_objects = 8 + self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') + self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') + def tearDown(self): tm.close() @@ -443,7 +446,6 @@ def setUp(self): import matplotlib as mpl mpl.rcdefaults() - self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') self.ts = tm.makeTimeSeries() self.ts.name = 'ts' @@ -818,12 +820,13 @@ def test_hist_kwargs(self): self._check_text_labels(ax.yaxis.get_label(), 'Degree') tm.close() - ax = self.ts.plot(kind='hist', orientation='horizontal') - self._check_text_labels(ax.xaxis.get_label(), 'Degree') - tm.close() + if self.mpl_ge_1_3_1: + ax = self.ts.plot(kind='hist', orientation='horizontal') + self._check_text_labels(ax.xaxis.get_label(), 'Degree') + tm.close() - ax = self.ts.plot(kind='hist', align='left', stacked=True) - tm.close() + ax = self.ts.plot(kind='hist', align='left', stacked=True) + tm.close() @slow def test_hist_kde_color(self): @@ -961,9 +964,6 @@ def setUp(self): import matplotlib as mpl mpl.rcdefaults() - self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') - self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') - self.tdf = tm.makeTimeDataFrame() self.hexbin_df = DataFrame({"A": np.random.uniform(size=20), "B": np.random.uniform(size=20), @@ -2141,31 +2141,33 @@ def test_hist_df_coord(self): self._check_box_coord(axes[2].patches, expected_y=np.array([0, 0, 0, 0, 0]), expected_h=np.array([6, 7, 8, 9, 10])) - # horizontal - ax = df.plot(kind='hist', bins=5, orientation='horizontal') - self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(ax.patches[5:10], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(ax.patches[10:], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([6, 7, 8, 9, 10])) - - ax = df.plot(kind='hist', bins=5, stacked=True, orientation='horizontal') - self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(ax.patches[5:10], expected_x=np.array([10, 9, 8, 7, 6]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(ax.patches[10:], expected_x=np.array([18, 17, 16, 15, 14]), - expected_w=np.array([6, 7, 8, 9, 10])) - - axes = df.plot(kind='hist', bins=5, stacked=True, - subplots=True, orientation='horizontal') - self._check_box_coord(axes[0].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(axes[1].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(axes[2].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([6, 7, 8, 9, 10])) + if self.mpl_ge_1_3_1: + + # horizontal + ax = df.plot(kind='hist', bins=5, orientation='horizontal') + self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(ax.patches[5:10], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(ax.patches[10:], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([6, 7, 8, 9, 10])) + + ax = df.plot(kind='hist', bins=5, stacked=True, orientation='horizontal') + self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(ax.patches[5:10], expected_x=np.array([10, 9, 8, 7, 6]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(ax.patches[10:], expected_x=np.array([18, 17, 16, 15, 14]), + expected_w=np.array([6, 7, 8, 9, 10])) + + axes = df.plot(kind='hist', bins=5, stacked=True, + subplots=True, orientation='horizontal') + self._check_box_coord(axes[0].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(axes[1].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(axes[2].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([6, 7, 8, 9, 10])) @slow def test_hist_df_legacy(self):
closes #8947 add SLOW build (optional)
https://api.github.com/repos/pandas-dev/pandas/pulls/8949
2014-11-30T23:00:05Z
2014-11-30T23:37:41Z
2014-11-30T23:37:41Z
2014-11-30T23:37:41Z
BUG: preserve left frame order in left merge
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index fc560782816ff..9c585cebcbe18 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -101,6 +101,7 @@ Bug Fixes - ``slice`` string method now takes step into account (:issue:`8754`) - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) +- Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py index 2f0920b6d4e98..e19c0de884c31 100644 --- a/pandas/tools/merge.py +++ b/pandas/tools/merge.py @@ -479,8 +479,10 @@ def _get_join_indexers(left_keys, right_keys, sort=False, how='inner'): left_group_key, right_group_key, max_groups = \ _factorize_keys(left_group_key, right_group_key, sort=sort) + # preserve left frame order if how == 'left' and sort == False + kwargs = {'sort':sort} if how == 'left' else {} join_func = _join_functions[how] - return join_func(left_group_key, right_group_key, max_groups) + return join_func(left_group_key, right_group_key, max_groups, **kwargs) class _OrderedMerge(_MergeOperation): diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index c942998d430f4..96e4b32d2ad25 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1022,6 +1022,13 @@ def test_left_join_index_multi_match_multiindex(self): tm.assert_frame_equal(result, expected) + # GH7331 - maintain left frame order in left merge + right.reset_index(inplace=True) + right.columns = left.columns[:3].tolist() + right.columns[-1:].tolist() + result = merge(left, right, how='left', on=left.columns[:-1].tolist()) + expected.index = np.arange(len(expected)) + tm.assert_frame_equal(result, expected) + def test_left_join_index_multi_match(self): left = DataFrame([ ['c', 0], @@ -1059,6 +1066,11 @@ def test_left_join_index_multi_match(self): tm.assert_frame_equal(result, expected) + # GH7331 - maintain left frame order in left merge + result = merge(left, right.reset_index(), how='left', on='tag') + expected.index = np.arange(len(expected)) + tm.assert_frame_equal(result, expected) + def test_join_multi_dtypes(self): # test with multi dtypes in the join index
closes https://github.com/pydata/pandas/issues/7331 on master: ``` >>> left dates states 0 20140101 CA 1 20140102 NY 2 20140103 CA >>> right stateid states 0 1 CA 1 2 NY >>> pd.merge(left, right, how='left', on='states', sort=False) dates states stateid 0 20140101 CA 1 1 20140103 CA 1 2 20140102 NY 2 ``` `DataFrame.join` already works fine: ``` >>> left.join(right.set_index('states'), on='states', how='left') dates states stateid 0 20140101 CA 1 1 20140102 NY 2 2 20140103 CA 1 ``` on branch: ``` >>> pd.merge(left, right, how='left', on='states', sort=False) dates states stateid 0 20140101 CA 1 1 20140102 NY 2 2 20140103 CA 1 >>> pd.merge(left, right, how='left', on='states', sort=True) dates states stateid 0 20140101 CA 1 1 20140103 CA 1 2 20140102 NY 2 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8948
2014-11-30T22:20:32Z
2014-12-01T00:46:44Z
2014-12-01T00:46:44Z
2014-12-01T12:54:02Z
API: Allow equality comparisons of Series with a categorical dtype and object type are allowed (GH8938)
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index a7091d6ab38fb..2a4c78ad837d1 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -328,13 +328,23 @@ old categories must be included in the new categories and no new categories are Comparisons ----------- -Comparing `Categoricals` with other objects is possible in two cases: +Comparing categorical data with other objects is possible in three cases: - * comparing a categorical Series to another categorical Series, when `categories` and `ordered` is - the same or - * comparing a categorical Series to a scalar. + * comparing equality (``==`` and ``!=``) to a list-like object (list, Series, array, + ...) of the same length as the categorical data or + * all comparisons (``==``, ``!=``, ``>``, ``>=``, ``<``, and ``<=``) of categorical data to + another categorical Series, when ``ordered==True`` and the `categories` are the same or + * all comparisons of a categorical data to a scalar. -All other comparisons will raise a TypeError. +All other comparisons, especially "non-equality" comparisons of two categoricals with different +categories or a categorical with any list-like object, will raise a TypeError. + +.. note:: + + Any "non-equality" comparisons of categorical data with a `Series`, `np.array`, `list` or + categorical data with different categories or ordering will raise an `TypeError` because custom + categories ordering could be interpreted in two ways: one with taking in account the + ordering and one without. .. ipython:: python @@ -353,6 +363,13 @@ Comparing to a categorical with the same categories and ordering or to a scalar cat > cat_base cat > 2 +Equality comparisons work with any list-like object of same length and scalars: + +.. ipython:: python + + cat == cat_base2 + cat == 2 + This doesn't work because the categories are not the same: .. ipython:: python @@ -362,13 +379,9 @@ This doesn't work because the categories are not the same: except TypeError as e: print("TypeError: " + str(e)) -.. note:: - - Comparisons with `Series`, `np.array` or a `Categorical` with different categories or ordering - will raise an `TypeError` because custom categories ordering could be interpreted in two ways: - one with taking in account the ordering and one without. If you want to compare a categorical - series with such a type, you need to be explicit and convert the categorical data back to the - original values: +If you want to do a "non-equality" comparison of a categorical series with a list-like object +which is not categorical data, you need to be explicit and convert the categorical data back to +the original values: .. ipython:: python diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 11cf2450d2f28..e61ae93ca49c0 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -59,6 +59,8 @@ API changes p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) p.all() +- Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 5b3e9e8a22b12..ff1051dc00a00 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -64,6 +64,12 @@ def f(self, other): else: return np.repeat(False, len(self)) else: + + # allow categorical vs object dtype array comparisons for equality + # these are only positional comparisons + if op in ['__eq__','__ne__']: + return getattr(np.array(self),op)(np.array(other)) + msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ "compare values, use 'np.asarray(cat) <op> other'." raise TypeError(msg.format(op=op,typ=type(other))) diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 068cdff7fcf2d..a3154ff9df9a1 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -541,10 +541,13 @@ def _comp_method_SERIES(op, name, str_rep, masker=False): """ def na_op(x, y): - if com.is_categorical_dtype(x) != (not np.isscalar(y) and com.is_categorical_dtype(y)): - msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ - "compare values, use 'series <op> np.asarray(cat)'." - raise TypeError(msg.format(op=op,typ=type(y))) + # dispatch to the categorical if we have a categorical + # in either operand + if com.is_categorical_dtype(x): + return op(x,y) + elif com.is_categorical_dtype(y) and not lib.isscalar(y): + return op(y,x) + if x.dtype == np.object_: if isinstance(y, list): y = lib.list_to_object_array(y) @@ -586,33 +589,33 @@ def wrapper(self, other): msg = "Cannot compare a Categorical for op {op} with Series of dtype {typ}.\n"\ "If you want to compare values, use 'series <op> np.asarray(other)'." raise TypeError(msg.format(op=op,typ=self.dtype)) - else: - mask = isnull(self) - values = self.get_values() - other = _index.convert_scalar(values,_values_from_object(other)) + mask = isnull(self) - if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): - values = values.view('i8') + values = self.get_values() + other = _index.convert_scalar(values,_values_from_object(other)) - # scalars - res = na_op(values, other) - if np.isscalar(res): - raise TypeError('Could not compare %s type with Series' - % type(other)) + if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): + values = values.view('i8') - # always return a full value series here - res = _values_from_object(res) + # scalars + res = na_op(values, other) + if np.isscalar(res): + raise TypeError('Could not compare %s type with Series' + % type(other)) - res = pd.Series(res, index=self.index, name=self.name, - dtype='bool') + # always return a full value series here + res = _values_from_object(res) - # mask out the invalids - if mask.any(): - res[mask] = masker + res = pd.Series(res, index=self.index, name=self.name, + dtype='bool') + + # mask out the invalids + if mask.any(): + res[mask] = masker - return res + return res return wrapper diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 196ad8b7680b9..4c202a525863d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -2211,11 +2211,63 @@ def f(): tm.assert_series_equal(res, exp) # And test NaN handling... - cat = pd.Series(pd.Categorical(["a","b","c", np.nan])) + cat = Series(Categorical(["a","b","c", np.nan])) exp = Series([True, True, True, False]) res = (cat == cat) tm.assert_series_equal(res, exp) + def test_cat_equality(self): + + # GH 8938 + # allow equality comparisons + a = Series(list('abc'),dtype="category") + b = Series(list('abc'),dtype="object") + c = Series(['a','b','cc'],dtype="object") + d = Series(list('acb'),dtype="object") + e = Categorical(list('abc')) + f = Categorical(list('acb')) + + # vs scalar + self.assertFalse((a=='a').all()) + self.assertTrue(((a!='a') == ~(a=='a')).all()) + + self.assertFalse(('a'==a).all()) + self.assertTrue((a=='a')[0]) + self.assertTrue(('a'==a)[0]) + self.assertFalse(('a'!=a)[0]) + + # vs list-like + self.assertTrue((a==a).all()) + self.assertFalse((a!=a).all()) + + self.assertTrue((a==list(a)).all()) + self.assertTrue((a==b).all()) + self.assertTrue((b==a).all()) + self.assertTrue(((~(a==b))==(a!=b)).all()) + self.assertTrue(((~(b==a))==(b!=a)).all()) + + self.assertFalse((a==c).all()) + self.assertFalse((c==a).all()) + self.assertFalse((a==d).all()) + self.assertFalse((d==a).all()) + + # vs a cat-like + self.assertTrue((a==e).all()) + self.assertTrue((e==a).all()) + self.assertFalse((a==f).all()) + self.assertFalse((f==a).all()) + + self.assertTrue(((~(a==e)==(a!=e)).all())) + self.assertTrue(((~(e==a)==(e!=a)).all())) + self.assertTrue(((~(a==f)==(a!=f)).all())) + self.assertTrue(((~(f==a)==(f!=a)).all())) + + # non-equality is not comparable + self.assertRaises(TypeError, lambda: a < b) + self.assertRaises(TypeError, lambda: b < a) + self.assertRaises(TypeError, lambda: a > b) + self.assertRaises(TypeError, lambda: b > a) + def test_concat(self): cat = pd.Categorical(["a","b"], categories=["a","b"]) vals = [1,2]
closes #8938
https://api.github.com/repos/pandas-dev/pandas/pulls/8946
2014-11-30T16:00:05Z
2014-12-04T11:06:12Z
2014-12-04T11:06:12Z
2014-12-05T15:46:03Z
BUG: Resample across multiple days
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3aa50ad609064..d111dc34995d2 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -145,7 +145,8 @@ Bug Fixes - +- Bug in resample that causes a ValueError when resampling across multiple days + and the last offset is not calculated from the start of the range (:issue:`8683`) - Bug in `pd.infer_freq`/`DataFrame.inferred_freq` that prevented proper sub-daily frequency inference diff --git a/pandas/tseries/resample.py b/pandas/tseries/resample.py index b362c55b156a4..95d3ff015394a 100644 --- a/pandas/tseries/resample.py +++ b/pandas/tseries/resample.py @@ -411,15 +411,19 @@ def _get_range_edges(first, last, offset, closed='left', base=0): def _adjust_dates_anchored(first, last, offset, closed='right', base=0): from pandas.tseries.tools import normalize_date + # First and last offsets should be calculated from the start day to fix an + # error cause by resampling across multiple days when a one day period is + # not a multiple of the frequency. + # + # See https://github.com/pydata/pandas/issues/8683 + start_day_nanos = Timestamp(normalize_date(first)).value - last_day_nanos = Timestamp(normalize_date(last)).value base_nanos = (base % offset.n) * offset.nanos // offset.n start_day_nanos += base_nanos - last_day_nanos += base_nanos foffset = (first.value - start_day_nanos) % offset.nanos - loffset = (last.value - last_day_nanos) % offset.nanos + loffset = (last.value - start_day_nanos) % offset.nanos if closed == 'right': if foffset > 0: diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index bd6c1766cfd61..42b09b699b919 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -705,6 +705,29 @@ def test_resample_anchored_monthstart(self): for freq in freqs: result = ts.resample(freq, how='mean') + def test_resample_anchored_multiday(self): + # When resampling a range spanning multiple days, ensure that the + # start date gets used to determine the offset. Fixes issue where + # a one day period is not a multiple of the frequency. + # + # See: https://github.com/pydata/pandas/issues/8683 + + s = pd.Series(np.random.randn(5), + index=pd.date_range('2014-10-14 23:06:23.206', + periods=3, freq='400L') + | pd.date_range('2014-10-15 23:00:00', + periods=2, freq='2200L')) + + # Ensure left closing works + result = s.resample('2200L', 'mean') + self.assertEqual(result.index[-1], + pd.Timestamp('2014-10-15 23:00:02.000')) + + # Ensure right closing works + result = s.resample('2200L', 'mean', label='right') + self.assertEqual(result.index[-1], + pd.Timestamp('2014-10-15 23:00:04.200')) + def test_corner_cases(self): # miscellaneous test coverage
Fixes an issue where resampling over multiple days causes a ValueError when a number of days between the normalized first and normalized last days is not a multiple of the frequency. Added test TestSeries.test_resample Closes #8683
https://api.github.com/repos/pandas-dev/pandas/pulls/8941
2014-11-30T13:33:57Z
2014-11-30T23:21:01Z
2014-11-30T23:21:01Z
2014-11-30T23:21:01Z
BUG: Fixed font size (set it on both x and y axis). #8765
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index eacccaa7cba92..f3f5cf41676da 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -99,6 +99,7 @@ Bug Fixes - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Fix negative step support for label-based slices (:issue:`8753`) +- Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) Old behavior: diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index cb669b75e5c96..4f3aa4e8e4a9e 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1051,13 +1051,15 @@ def _adorn_subplots(self): xticklabels = [labels.get(x, '') for x in ax.get_xticks()] ax.set_xticklabels(xticklabels) self._apply_axis_properties(ax.xaxis, rot=self.rot, - fontsize=self.fontsize) + fontsize=self.fontsize) + self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize) elif self.orientation == 'horizontal': if self._need_to_set_index: yticklabels = [labels.get(y, '') for y in ax.get_yticks()] ax.set_yticklabels(yticklabels) self._apply_axis_properties(ax.yaxis, rot=self.rot, - fontsize=self.fontsize) + fontsize=self.fontsize) + self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize) def _apply_axis_properties(self, axis, rot=None, fontsize=None): labels = axis.get_majorticklabels() + axis.get_minorticklabels() diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index 4a60cdbedae4d..c4e642ffe43b0 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -48,6 +48,14 @@ def test_ts_plot_with_tz(self): ts = Series([188.5, 328.25], index=index) _check_plot_works(ts.plot) + def test_fontsize_set_correctly(self): + # For issue #8765 + import matplotlib.pyplot as plt + df = DataFrame(np.random.randn(10, 9), index=range(10)) + ax = df.plot(fontsize=2) + for label in (ax.get_xticklabels() + ax.get_yticklabels()): + self.assertEqual(label.get_fontsize(), 2) + @slow def test_frame_inferred(self): # inferred freq
Fix for https://github.com/pydata/pandas/issues/8765 The font size was only set on x axis if vertical or the y axis if horizontal.
https://api.github.com/repos/pandas-dev/pandas/pulls/8940
2014-11-30T12:41:40Z
2014-12-01T00:08:43Z
2014-12-01T00:08:43Z
2014-12-01T00:08:43Z