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 |
|---|---|---|---|---|---|---|---|
CLN: Use to_numpy directly in cov / corr | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2d181e826c2a9..839f56db2365e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7975,7 +7975,7 @@ 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.astype(float, copy=False).to_numpy()
+ mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
@@ -8110,7 +8110,7 @@ def cov(self, min_periods=None) -> "DataFrame":
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
- mat = numeric_df.astype(float, copy=False).to_numpy()
+ mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
| https://api.github.com/repos/pandas-dev/pandas/pulls/34031 | 2020-05-06T17:02:40Z | 2020-05-23T07:45:50Z | 2020-05-23T07:45:50Z | 2020-05-23T15:12:15Z | |
TST: Add Series.update ExtensionArray tests | diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index 9cb6d8f81fff7..d00a4299cb690 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import CategoricalDtype, DataFrame, NaT, Series, Timestamp
import pandas._testing as tm
@@ -93,6 +93,16 @@ def test_update_from_non_series(self, series, other, expected):
Series([None, False], dtype="boolean"),
Series([True, False], dtype="boolean"),
),
+ (
+ Series(["a", None], dtype=CategoricalDtype(categories=["a", "b"])),
+ Series([None, "b"], dtype=CategoricalDtype(categories=["a", "b"])),
+ Series(["a", "b"], dtype=CategoricalDtype(categories=["a", "b"])),
+ ),
+ (
+ Series([Timestamp(year=2020, month=1, day=1, tz="Europe/London"), NaT]),
+ Series([NaT, Timestamp(year=2020, month=1, day=1, tz="Europe/London")]),
+ Series([Timestamp(year=2020, month=1, day=1, tz="Europe/London")] * 2),
+ ),
],
)
def test_update_extension_array_series(self, result, target, expected):
| cc @simonjayhawkins
xref https://github.com/pandas-dev/pandas/issues/25744 https://github.com/pandas-dev/pandas/issues/34020
I think the dtype issue for DataFrame.update with categorical columns mentioned in the first issue is still unaddressed, so likely don't want to only close and lose that (perhaps break into its own issue)? | https://api.github.com/repos/pandas-dev/pandas/pulls/34030 | 2020-05-06T16:58:23Z | 2020-05-10T17:09:38Z | 2020-05-10T17:09:38Z | 2020-05-10T17:39:22Z |
Backport PR #33693 on branch 1.0.x (BUG: Fix memory issues in rolling… | diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index 7a72622fd5fe3..331086b773eea 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -129,19 +129,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)()
from .pandas_vb_common import setup # noqa: F401 isort:skip
diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 80f8976826bc8..219f3459aa09c 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -27,7 +27,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
--
+- Bug in :meth:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`)
-
Contributors
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 495b436030120..e998c7e31bd49 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -965,8 +965,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.
@@ -982,7 +982,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,
@@ -1005,8 +1005,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.
@@ -1019,7 +1019,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,
@@ -1121,9 +1121,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):
| ….min/max)
xref https://github.com/pandas-dev/pandas/pull/33693#issuecomment-619536995 | https://api.github.com/repos/pandas-dev/pandas/pulls/34027 | 2020-05-06T14:41:33Z | 2020-05-06T16:08:28Z | 2020-05-06T16:08:28Z | 2020-05-06T16:08:51Z |
Backport PR #32905 on branch 1.0.x (Fix to _get_nearest_indexer for p… | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 80f8976826bc8..2852b3b4fe92c 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -21,6 +21,7 @@ Fixed regressions
- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
+- Fix to preserve the ability to index with the "nearest" method with xarray's CFTimeIndex, an :class:`Index` subclass (`pydata/xarray#3751 <https://github.com/pydata/xarray/issues/3751>`_, :issue:`32905`).
-
.. _whatsnew_104.bug_fixes:
diff --git a/environment.yml b/environment.yml
index 3c7aed32af3f8..ea15bf1bffe1f 100644
--- a/environment.yml
+++ b/environment.yml
@@ -102,6 +102,7 @@ dependencies:
- s3fs # pandas.read_csv... when using 's3://...' path
- sqlalchemy # pandas.read_sql, DataFrame.to_sql
- xarray # DataFrame.to_xarray
+ - cftime # Needed for downstream xarray.CFTimeIndex test
- pyreadstat # pandas.read_spss
- tabulate>=0.8.3 # DataFrame.to_markdown
- pip:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 38f8521bfa2d4..5ff8f590e78aa 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2817,8 +2817,9 @@ def _get_nearest_indexer(self, target, limit, tolerance):
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
- left_distances = np.abs(self[left_indexer] - target)
- right_distances = np.abs(self[right_indexer] - target)
+ target_values = target._values
+ left_distances = np.abs(self._values[left_indexer] - target_values)
+ right_distances = np.abs(self._values[right_indexer] - target_values)
op = operator.lt if self.is_monotonic_increasing else operator.le
indexer = np.where(
@@ -2827,11 +2828,11 @@ def _get_nearest_indexer(self, target, limit, tolerance):
right_indexer,
)
if tolerance is not None:
- indexer = self._filter_indexer_tolerance(target, indexer, tolerance)
+ indexer = self._filter_indexer_tolerance(target_values, indexer, tolerance)
return indexer
def _filter_indexer_tolerance(self, target, indexer, tolerance):
- distance = abs(self.values[indexer] - target)
+ distance = abs(self._values[indexer] - target)
indexer = np.where(distance <= tolerance, indexer, -1)
return indexer
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index d4d7803a724e2..9f473d1ad4df6 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -8,6 +8,8 @@
import numpy as np # noqa
import pytest
+import pandas.util._test_decorators as td
+
from pandas import DataFrame, Series
import pandas._testing as tm
@@ -47,6 +49,19 @@ def test_xarray(df):
assert df.to_xarray() is not None
+@td.skip_if_no("cftime")
+@td.skip_if_no("xarray", "0.10.4")
+def test_xarray_cftimeindex_nearest():
+ # https://github.com/pydata/xarray/issues/3751
+ import cftime
+ import xarray
+
+ times = xarray.cftime_range("0001", periods=2)
+ result = times.get_loc(cftime.DatetimeGregorian(2000, 1, 1), method="nearest")
+ expected = 1
+ assert result == expected
+
+
def test_oo_optimizable():
# GH 21071
subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"])
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 3089b96d26780..0b8236c4fd1d2 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -69,6 +69,7 @@ tables>=3.4.2
s3fs
sqlalchemy
xarray
+cftime
pyreadstat
tabulate>=0.8.3
git+https://github.com/pandas-dev/pydata-sphinx-theme.git@master
\ No newline at end of file
| …ydata/xarray#3751)
xref #32905
regression in 1.0.2 (backport of #31511) | https://api.github.com/repos/pandas-dev/pandas/pulls/34025 | 2020-05-06T14:31:30Z | 2020-05-06T15:20:48Z | 2020-05-06T15:20:48Z | 2020-05-06T15:20:53Z |
CLN: remove _typ checks in Timestamp methods | diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx
index 68987030e8b4e..cde2c2573072f 100644
--- a/pandas/_libs/tslibs/c_timestamp.pyx
+++ b/pandas/_libs/tslibs/c_timestamp.pyx
@@ -251,9 +251,11 @@ cdef class _Timestamp(datetime):
# delta --> offsets.Tick
# logic copied from delta_to_nanoseconds to prevent circular import
if hasattr(other, 'nanos'):
+ # Tick
nanos = other.nanos
elif hasattr(other, 'delta'):
- nanos = other.delta
+ # pd.Timedelta
+ nanos = other.value
elif PyDelta_Check(other):
nanos = (other.days * 24 * 60 * 60 * 1000000 +
other.seconds * 1000000 +
@@ -273,15 +275,7 @@ cdef class _Timestamp(datetime):
dtype=object,
)
- # index/series like
- elif hasattr(other, '_typ'):
- return NotImplemented
-
- result = datetime.__add__(self, other)
- if PyDateTime_Check(result):
- result = type(self)(result)
- result.nanosecond = self.nanosecond
- return result
+ return NotImplemented
def __sub__(self, other):
@@ -301,9 +295,6 @@ cdef class _Timestamp(datetime):
[self - other[n] for n in range(len(other))],
dtype=object,
)
-
- typ = getattr(other, '_typ', None)
- if typ is not None:
return NotImplemented
if other is NaT:
@@ -339,6 +330,8 @@ cdef class _Timestamp(datetime):
"to datetime.datetime with 'Timestamp.to_pydatetime()' "
"before subtracting."
) from err
+ # We get here in stata tests, fall back to stdlib datetime
+ # method and return stdlib timedelta object
pass
elif is_datetime64_object(self):
# GH#28286 cython semantics for __rsub__, `other` is actually
| https://api.github.com/repos/pandas-dev/pandas/pulls/34024 | 2020-05-06T14:20:48Z | 2020-05-06T16:48:49Z | 2020-05-06T16:48:49Z | 2020-05-06T17:23:44Z | |
Backport PR #33089 on branch 1.0.x (BUG: Don't cast nullable Boolean to float in groupby) | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index d4f4e9c0ae8de..4f122b0dea5f4 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -21,6 +21,7 @@ Fixed regressions
- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
+- Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
- Fix to preserve the ability to index with the "nearest" method with xarray's CFTimeIndex, an :class:`Index` subclass (`pydata/xarray#3751 <https://github.com/pydata/xarray/issues/3751>`_, :issue:`32905`).
-
@@ -28,6 +29,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
+- Bug in :meth:`SeriesGroupBy.first`, :meth:`SeriesGroupBy.last`, :meth:`SeriesGroupBy.min`, and :meth:`SeriesGroupBy.max` returning floats when applied to nullable Booleans (:issue:`33071`)
- Bug in :meth:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`)
-
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 57d865a051c31..478239b1bcff0 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -42,6 +42,7 @@ class providing the base-class of operations.
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
from pandas.core.dtypes.common import (
ensure_float,
+ is_categorical_dtype,
is_datetime64_dtype,
is_extension_array_dtype,
is_integer_dtype,
@@ -807,15 +808,15 @@ def _try_cast(self, result, obj, numeric_only: bool = False):
dtype = obj.dtype
if not is_scalar(result):
- if is_extension_array_dtype(dtype) and dtype.kind != "M":
- # The function can return something of any type, so check
- # if the type is compatible with the calling EA.
- # datetime64tz is handled correctly in agg_series,
- # so is excluded here.
-
- if len(result) and isinstance(result[0], dtype.type):
- cls = dtype.construct_array_type()
- result = try_cast_to_ea(cls, result, dtype=dtype)
+ if (
+ is_extension_array_dtype(dtype)
+ and not is_categorical_dtype(dtype)
+ and dtype.kind != "M"
+ ):
+ # We have to special case categorical so as not to upcast
+ # things like counts back to categorical
+ cls = dtype.construct_array_type()
+ result = try_cast_to_ea(cls, result, dtype=dtype)
elif numeric_only and is_numeric_dtype(dtype) or not numeric_only:
result = maybe_downcast_to_dtype(result, dtype)
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 7b2e3f7a7e06a..947907caf5cbc 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -395,6 +395,32 @@ def test_first_last_tz_multi_column(method, ts, alpha):
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize(
+ "values",
+ [
+ pd.array([True, False], dtype="boolean"),
+ pd.array([1, 2], dtype="Int64"),
+ pd.to_datetime(["2020-01-01", "2020-02-01"]),
+ pd.to_timedelta([1, 2], unit="D"),
+ ],
+)
+@pytest.mark.parametrize("function", ["first", "last", "min", "max"])
+def test_first_last_extension_array_keeps_dtype(values, function):
+ # https://github.com/pandas-dev/pandas/issues/33071
+ # https://github.com/pandas-dev/pandas/issues/32194
+ df = DataFrame({"a": [1, 2], "b": values})
+ grouped = df.groupby("a")
+ idx = Index([1, 2], name="a")
+ expected_series = Series(values, name="b", index=idx)
+ expected_frame = DataFrame({"b": values}, index=idx)
+
+ result_series = getattr(grouped["b"], function)()
+ tm.assert_series_equal(result_series, expected_series)
+
+ result_frame = grouped.agg({"b": function})
+ tm.assert_frame_equal(result_frame, expected_frame)
+
+
def test_nth_multi_index_as_expected():
# PR 9090, related to issue 8979
# test nth on MultiIndex
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 3ad82b9e075a8..ab6985b11ba9a 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -122,9 +122,7 @@ def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
- [1, 4, 7],
- index=pd.date_range("1/1/2000", periods=3, freq="3T"),
- dtype="float64",
+ [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64",
)
tm.assert_series_equal(result, expected)
| xref #33089
regression in 1.0.0, xref https://github.com/pandas-dev/pandas/issues/32194#issuecomment-604664466
# NOTE: same code fix, different location
cc @dsaxton | https://api.github.com/repos/pandas-dev/pandas/pulls/34023 | 2020-05-06T13:34:58Z | 2020-05-07T10:10:20Z | 2020-05-07T10:10:20Z | 2020-05-07T10:10:26Z |
Backport PR #33513 on branch 1.0.x (BUG: Fix Categorical.min / max bug) | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 48680d2b698a8..80f8976826bc8 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -20,6 +20,7 @@ Fixed regressions
- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
+- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
-
.. _whatsnew_104.bug_fixes:
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 756896279054c..f7e2ebdc8a17a 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2151,7 +2151,7 @@ def min(self, skipna=True):
good = self._codes != -1
if not good.all():
- if skipna:
+ if skipna and good.any():
pointer = self._codes[good].min()
else:
return np.nan
@@ -2186,7 +2186,7 @@ def max(self, skipna=True):
good = self._codes != -1
if not good.all():
- if skipna:
+ if skipna and good.any():
pointer = self._codes[good].max()
else:
return np.nan
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index 90fcf12093909..6af3d18fa24ff 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -88,6 +88,14 @@ def test_min_max_with_nan(self, skipna):
assert _min == 2
assert _max == 1
+ @pytest.mark.parametrize("function", ["min", "max"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_min_max_only_nan(self, function, skipna):
+ # https://github.com/pandas-dev/pandas/issues/33450
+ cat = Categorical([np.nan], categories=[1, 2], ordered=True)
+ result = getattr(cat, function)(skipna=skipna)
+ assert result is np.nan
+
@pytest.mark.parametrize("method", ["min", "max"])
def test_deprecate_numeric_only_min_max(self, method):
# GH 25303
| xref #33513
regression in #27929 (i.e. 1.0.0) https://github.com/pandas-dev/pandas/issues/33450#issuecomment-624625326 | https://api.github.com/repos/pandas-dev/pandas/pulls/34022 | 2020-05-06T12:03:08Z | 2020-05-06T12:44:27Z | 2020-05-06T12:44:27Z | 2020-05-06T12:44:33Z |
TST: query with timezone aware index & column | diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index 8612c05e6a996..89f268f8b6bc6 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -695,6 +695,21 @@ def test_inf(self):
result = df.query(q, engine=self.engine, parser=self.parser)
tm.assert_frame_equal(result, expected)
+ def test_check_tz_aware_index_query(self, tz_aware_fixture):
+ # https://github.com/pandas-dev/pandas/issues/29463
+ tz = tz_aware_fixture
+ df_index = pd.date_range(
+ start="2019-01-01", freq="1d", periods=10, tz=tz, name="time"
+ )
+ expected = pd.DataFrame(index=df_index)
+ df = pd.DataFrame(index=df_index)
+ result = df.query('"2018-01-03 00:00:00+00" < time')
+ tm.assert_frame_equal(result, expected)
+
+ expected = pd.DataFrame(df_index)
+ result = df.reset_index().query('"2018-01-03 00:00:00+00" < time')
+ tm.assert_frame_equal(result, expected)
+
@td.skip_if_no_ne
class TestDataFrameQueryNumExprPython(TestDataFrameQueryNumExprPandas):
| - [X] closes #29463
- [X] tests added / passed
- [X] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/34021 | 2020-05-06T11:14:28Z | 2020-05-20T05:40:37Z | 2020-05-20T05:40:36Z | 2020-05-20T05:47:18Z |
CLN: remove normalize_datetime | diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py
index 4a4e53eaa45fa..47b35aa6eabff 100644
--- a/pandas/_libs/tslibs/__init__.py
+++ b/pandas/_libs/tslibs/__init__.py
@@ -1,6 +1,5 @@
__all__ = [
"localize_pydatetime",
- "normalize_date",
"NaT",
"NaTType",
"iNaT",
@@ -17,7 +16,7 @@
]
-from .conversion import localize_pydatetime, normalize_date
+from .conversion import localize_pydatetime
from .nattype import NaT, NaTType, iNaT, is_null_datetimelike
from .np_datetime import OutOfBoundsDatetime
from .period import IncompatibleFrequency, Period
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index f7408e69f7dec..8a1cacfe304ca 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1,5 +1,5 @@
from datetime import datetime, time, timedelta
-from typing import Union
+from typing import Optional, Union
import warnings
import numpy as np
@@ -13,7 +13,6 @@
conversion,
fields,
iNaT,
- normalize_date,
resolution as libresolution,
timezones,
tzconversion,
@@ -2288,19 +2287,21 @@ def _infer_tz_from_endpoints(start, end, tz):
return tz
-def _maybe_normalize_endpoints(start, end, normalize):
+def _maybe_normalize_endpoints(
+ start: Optional[Timestamp], end: Optional[Timestamp], normalize: bool
+):
_normalized = True
if start is not None:
if normalize:
- start = normalize_date(start)
+ start = start.normalize()
_normalized = True
else:
_normalized = _normalized and start.time() == _midnight
if end is not None:
if normalize:
- end = normalize_date(end)
+ end = end.normalize()
_normalized = True
else:
_normalized = _normalized and end.time() == _midnight
diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py
index 7a8a6d511aa69..a4c2e3f0787d0 100644
--- a/pandas/tests/tslibs/test_api.py
+++ b/pandas/tests/tslibs/test_api.py
@@ -38,7 +38,6 @@ def test_namespace():
"delta_to_nanoseconds",
"ints_to_pytimedelta",
"localize_pydatetime",
- "normalize_date",
"tz_convert_single",
]
diff --git a/pandas/tests/tslibs/test_normalize_date.py b/pandas/tests/tslibs/test_normalize_date.py
deleted file mode 100644
index 2a41836f456ec..0000000000000
--- a/pandas/tests/tslibs/test_normalize_date.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Tests for functions from pandas._libs.tslibs"""
-
-from datetime import date, datetime
-
-import pytest
-
-from pandas._libs import tslibs
-from pandas._libs.tslibs.timestamps import Timestamp
-
-
-@pytest.mark.parametrize(
- "value,expected",
- [
- (date(2012, 9, 7), datetime(2012, 9, 7)),
- (datetime(2012, 9, 7, 12), datetime(2012, 9, 7)),
- (datetime(2007, 10, 1, 1, 12, 5, 10), datetime(2007, 10, 1)),
- ],
-)
-def test_normalize_date(value, expected):
- result = tslibs.normalize_date(value)
- assert result == expected
-
-
-class SubDatetime(datetime):
- pass
-
-
-@pytest.mark.parametrize(
- "dt, expected",
- [
- (Timestamp(2000, 1, 1, 1), Timestamp(2000, 1, 1, 0)),
- (datetime(2000, 1, 1, 1), datetime(2000, 1, 1, 0)),
- (SubDatetime(2000, 1, 1, 1), SubDatetime(2000, 1, 1, 0)),
- ],
-)
-def test_normalize_date_sub_types(dt, expected):
- # GH 25851
- # ensure that subclassed datetime works with
- # normalize_date
- result = tslibs.normalize_date(dt)
- assert result == expected
| No longer necessary following #34006 | https://api.github.com/repos/pandas-dev/pandas/pulls/34016 | 2020-05-06T00:47:22Z | 2020-05-06T23:05:20Z | 2020-05-06T23:05:20Z | 2020-05-07T00:39:29Z |
REF: update iNaT imports | diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 53bcf5be2586a..556cab565860c 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -50,8 +50,7 @@ from pandas._libs.tslibs.conversion cimport (
_TSObject, convert_datetime_to_tsobject,
get_datetime64_nanos)
-# many modules still look for NaT and iNaT here despite them not being needed
-from pandas._libs.tslibs.nattype import nat_strings, iNaT # noqa:F821
+from pandas._libs.tslibs.nattype import nat_strings
from pandas._libs.tslibs.nattype cimport (
checknull_with_nat, NPY_NAT, c_NaT as NaT)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index cc0fdae094cf9..c2115094918e5 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -9,8 +9,7 @@
import numpy as np
-from pandas._libs import Timestamp, algos, hashtable as htable, lib
-from pandas._libs.tslib import iNaT
+from pandas._libs import Timestamp, algos, hashtable as htable, iNaT, lib
from pandas._typing import AnyArrayLike, ArrayLike, DtypeObj
from pandas.util._decorators import doc
diff --git a/pandas/tests/base/test_fillna.py b/pandas/tests/base/test_fillna.py
index 630ecdacd91d1..c6f58af4c5c3a 100644
--- a/pandas/tests/base/test_fillna.py
+++ b/pandas/tests/base/test_fillna.py
@@ -6,7 +6,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.core.dtypes.common import needs_i8_conversion
from pandas.core.dtypes.generic import ABCMultiIndex
diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py
index eca402af252f8..9703faff40aff 100644
--- a/pandas/tests/base/test_unique.py
+++ b/pandas/tests/base/test_unique.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.core.dtypes.common import is_datetime64tz_dtype, needs_i8_conversion
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
index 2514b11613ef6..de04c30432e6f 100644
--- a/pandas/tests/base/test_value_counts.py
+++ b/pandas/tests/base/test_value_counts.py
@@ -5,7 +5,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.compat.numpy import np_array_datetime64_compat
from pandas.core.dtypes.common import needs_i8_conversion
diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py
index 11b41eedd5d51..b1eb276bfc227 100644
--- a/pandas/tests/extension/test_period.py
+++ b/pandas/tests/extension/test_period.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.core.dtypes.dtypes import PeriodDtype
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index ed3c4689c92d9..3865ea64ee479 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.core.dtypes.common import is_float_dtype, is_integer
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 8e8f4738d30dd..0f9509c372bdf 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
from pandas.core.dtypes.common import is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py
index caaffb7d5b61f..6d3c37659f5c4 100644
--- a/pandas/tests/series/methods/test_rank.py
+++ b/pandas/tests/series/methods/test_rank.py
@@ -3,8 +3,8 @@
import numpy as np
import pytest
+from pandas._libs import iNaT
from pandas._libs.algos import Infinity, NegInfinity
-from pandas._libs.tslib import iNaT
import pandas.util._test_decorators as td
from pandas import NaT, Series, Timestamp, date_range
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index d78324d92a036..1dd410ad02ee0 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -5,8 +5,7 @@
import numpy.ma as ma
import pytest
-from pandas._libs import lib
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT, lib
from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index a64a6bc584cf6..3b8c2e595148e 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -4,7 +4,7 @@
import pytest
import pytz
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
import pandas as pd
from pandas import (
diff --git a/pandas/tests/test_take.py b/pandas/tests/test_take.py
index 2534f1849cf61..2a42eb5d73136 100644
--- a/pandas/tests/test_take.py
+++ b/pandas/tests/test_take.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas._libs.tslib import iNaT
+from pandas._libs import iNaT
import pandas._testing as tm
import pandas.core.algorithms as algos
diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py
index 96c2d6bbd8106..d0066988faec7 100644
--- a/pandas/tests/tslibs/test_conversion.py
+++ b/pandas/tests/tslibs/test_conversion.py
@@ -4,8 +4,7 @@
import pytest
from pytz import UTC
-from pandas._libs.tslib import iNaT
-from pandas._libs.tslibs import conversion, timezones, tzconversion
+from pandas._libs.tslibs import conversion, iNaT, timezones, tzconversion
from pandas import Timestamp, date_range
import pandas._testing as tm
| https://api.github.com/repos/pandas-dev/pandas/pulls/34015 | 2020-05-06T00:32:35Z | 2020-05-06T23:04:22Z | 2020-05-06T23:04:22Z | 2020-05-07T00:41:59Z | |
ENH: Add compression to stata exporters | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 8526ccb57396f..9f0aaecacd383 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -227,7 +227,12 @@ Other enhancements
- The ``ExtensionArray`` class has now an :meth:`~pandas.arrays.ExtensionArray.equals`
method, similarly to :meth:`Series.equals` (:issue:`27081`).
- The minimum suppported dta version has increased to 105 in :meth:`~pandas.io.stata.read_stata` and :class:`~pandas.io.stata.StataReader` (:issue:`26667`).
-
+- :meth:`~pandas.core.frame.DataFrame.to_stata` supports compression using the ``compression``
+ keyword argument. Compression can either be inferred or explicitly set using a string or a
+ dictionary containing both the method and any additional arguments that are passed to the
+ compression library. Compression was also added to the low-level Stata-file writers
+ :class:`~pandas.io.stata.StataWriter`, :class:`~pandas.io.stata.StataWriter117`,
+ and :class:`~pandas.io.stata.StataWriterUTF8` (:issue:`26599`).
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 102b305cc7a99..445d168ff875d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -25,6 +25,7 @@
Iterable,
Iterator,
List,
+ Mapping,
Optional,
Sequence,
Set,
@@ -2015,6 +2016,7 @@ def to_stata(
variable_labels: Optional[Dict[Label, str]] = None,
version: Optional[int] = 114,
convert_strl: Optional[Sequence[Label]] = None,
+ compression: Union[str, Mapping[str, str], None] = "infer",
) -> None:
"""
Export DataFrame object to Stata dta format.
@@ -2078,6 +2080,19 @@ def to_stata(
.. versionadded:: 0.23.0
+ compression : str or dict, default 'infer'
+ For on-the-fly compression of the output dta. If string, specifies
+ compression mode. If dict, value at key 'method' specifies
+ compression mode. Compression mode must be one of {'infer', 'gzip',
+ 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and
+ `fname` is path-like, then detect compression from the following
+ extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no
+ compression). If dict and compression mode is one of {'zip',
+ 'gzip', 'bz2'}, or inferred as one of the above, other entries
+ passed as additional compression options.
+
+ .. versionadded:: 1.1.0
+
Raises
------
NotImplementedError
@@ -2133,6 +2148,7 @@ def to_stata(
data_label=data_label,
write_index=write_index,
variable_labels=variable_labels,
+ compression=compression,
**kwargs,
)
writer.write_file()
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 789e08d0652c9..fe8dcf1bdb9aa 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -16,7 +16,18 @@
from pathlib import Path
import struct
import sys
-from typing import Any, AnyStr, BinaryIO, Dict, List, Optional, Sequence, Tuple, Union
+from typing import (
+ Any,
+ AnyStr,
+ BinaryIO,
+ Dict,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
import warnings
from dateutil.relativedelta import relativedelta
@@ -47,7 +58,13 @@
from pandas.core.indexes.base import Index
from pandas.core.series import Series
-from pandas.io.common import get_filepath_or_buffer, stringify_path
+from pandas.io.common import (
+ get_compression_method,
+ get_filepath_or_buffer,
+ get_handle,
+ infer_compression,
+ stringify_path,
+)
_version_error = (
"Version of given Stata file is {version}. pandas supports importing "
@@ -1854,13 +1871,18 @@ def read_stata(
return data
-def _open_file_binary_write(fname: FilePathOrBuffer) -> Tuple[BinaryIO, bool]:
+def _open_file_binary_write(
+ fname: FilePathOrBuffer, compression: Union[str, Mapping[str, str], None],
+) -> Tuple[BinaryIO, bool, Optional[Union[str, Mapping[str, str]]]]:
"""
Open a binary file or no-op if file-like.
Parameters
----------
fname : string path, path object or buffer
+ The file name or buffer.
+ compression : {str, dict, None}
+ The compression method to use.
Returns
-------
@@ -1871,9 +1893,21 @@ def _open_file_binary_write(fname: FilePathOrBuffer) -> Tuple[BinaryIO, bool]:
"""
if hasattr(fname, "write"):
# See https://github.com/python/mypy/issues/1424 for hasattr challenges
- return fname, False # type: ignore
+ return fname, False, None # type: ignore
elif isinstance(fname, (str, Path)):
- return open(fname, "wb"), True
+ # Extract compression mode as given, if dict
+ compression_typ, compression_args = get_compression_method(compression)
+ compression_typ = infer_compression(fname, compression_typ)
+ path_or_buf, _, compression_typ, _ = get_filepath_or_buffer(
+ fname, compression=compression_typ
+ )
+ if compression_typ is not None:
+ compression = compression_args
+ compression["method"] = compression_typ
+ else:
+ compression = None
+ f, _ = get_handle(path_or_buf, "wb", compression=compression, is_text=False)
+ return f, True, compression
else:
raise TypeError("fname must be a binary file, buffer or path-like.")
@@ -2050,6 +2084,17 @@ class StataWriter(StataParser):
variable_labels : dict
Dictionary containing columns as keys and variable labels as values.
Each label must be 80 characters or smaller.
+ compression : str or dict, default 'infer'
+ For on-the-fly compression of the output dta. If string, specifies
+ compression mode. If dict, value at key 'method' specifies compression
+ mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip',
+ 'xz', None}. If compression mode is 'infer' and `fname` is path-like,
+ then detect compression from the following extensions: '.gz', '.bz2',
+ '.zip', or '.xz' (otherwise no compression). If dict and compression
+ mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above,
+ other entries passed as additional compression options.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -2074,7 +2119,12 @@ class StataWriter(StataParser):
>>> writer = StataWriter('./data_file.dta', data)
>>> writer.write_file()
- Or with dates
+ Directly write a zip file
+ >>> compression = {"method": "zip", "archive_name": "data_file.dta"}
+ >>> writer = StataWriter('./data_file.zip', data, compression=compression)
+ >>> writer.write_file()
+
+ Save a DataFrame with dates
>>> from datetime import datetime
>>> data = pd.DataFrame([[datetime(2000,1,1)]], columns=['date'])
>>> writer = StataWriter('./date_data_file.dta', data, {'date' : 'tw'})
@@ -2094,6 +2144,7 @@ def __init__(
time_stamp: Optional[datetime.datetime] = None,
data_label: Optional[str] = None,
variable_labels: Optional[Dict[Label, str]] = None,
+ compression: Union[str, Mapping[str, str], None] = "infer",
):
super().__init__()
self._convert_dates = {} if convert_dates is None else convert_dates
@@ -2102,6 +2153,8 @@ def __init__(
self._data_label = data_label
self._variable_labels = variable_labels
self._own_file = True
+ self._compression = compression
+ self._output_file: Optional[BinaryIO] = None
# attach nobs, nvars, data, varlist, typlist
self._prepare_pandas(data)
@@ -2389,7 +2442,12 @@ def _encode_strings(self) -> None:
self.data[col] = encoded
def write_file(self) -> None:
- self._file, self._own_file = _open_file_binary_write(self._fname)
+ self._file, self._own_file, compression = _open_file_binary_write(
+ self._fname, self._compression
+ )
+ if compression is not None:
+ self._output_file = self._file
+ self._file = BytesIO()
try:
self._write_header(data_label=self._data_label, time_stamp=self._time_stamp)
self._write_map()
@@ -2434,6 +2492,12 @@ def _close(self) -> None:
"""
# Some file-like objects might not support flush
assert self._file is not None
+ if self._output_file is not None:
+ assert isinstance(self._file, BytesIO)
+ bio = self._file
+ bio.seek(0)
+ self._file = self._output_file
+ self._file.write(bio.read())
try:
self._file.flush()
except AttributeError:
@@ -2898,6 +2962,17 @@ class StataWriter117(StataWriter):
Smaller columns can be converted by including the column name. Using
StrLs can reduce output file size when strings are longer than 8
characters, and either frequently repeated or sparse.
+ compression : str or dict, default 'infer'
+ For on-the-fly compression of the output dta. If string, specifies
+ compression mode. If dict, value at key 'method' specifies compression
+ mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip',
+ 'xz', None}. If compression mode is 'infer' and `fname` is path-like,
+ then detect compression from the following extensions: '.gz', '.bz2',
+ '.zip', or '.xz' (otherwise no compression). If dict and compression
+ mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above,
+ other entries passed as additional compression options.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -2923,8 +2998,12 @@ class StataWriter117(StataWriter):
>>> writer = StataWriter117('./data_file.dta', data)
>>> writer.write_file()
- Or with long strings stored in strl format
+ Directly write a zip file
+ >>> compression = {"method": "zip", "archive_name": "data_file.dta"}
+ >>> writer = StataWriter117('./data_file.zip', data, compression=compression)
+ >>> writer.write_file()
+ Or with long strings stored in strl format
>>> data = pd.DataFrame([['A relatively long string'], [''], ['']],
... columns=['strls'])
>>> writer = StataWriter117('./data_file_with_long_strings.dta', data,
@@ -2946,6 +3025,7 @@ def __init__(
data_label: Optional[str] = None,
variable_labels: Optional[Dict[Label, str]] = None,
convert_strl: Optional[Sequence[Label]] = None,
+ compression: Union[str, Mapping[str, str], None] = "infer",
):
# Copy to new list since convert_strl might be modified later
self._convert_strl: List[Label] = []
@@ -2961,6 +3041,7 @@ def __init__(
time_stamp=time_stamp,
data_label=data_label,
variable_labels=variable_labels,
+ compression=compression,
)
self._map: Dict[str, int] = {}
self._strl_blob = b""
@@ -3281,6 +3362,17 @@ class StataWriterUTF8(StataWriter117):
The dta version to use. By default, uses the size of data to determine
the version. 118 is used if data.shape[1] <= 32767, and 119 is used
for storing larger DataFrames.
+ compression : str or dict, default 'infer'
+ For on-the-fly compression of the output dta. If string, specifies
+ compression mode. If dict, value at key 'method' specifies compression
+ mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip',
+ 'xz', None}. If compression mode is 'infer' and `fname` is path-like,
+ then detect compression from the following extensions: '.gz', '.bz2',
+ '.zip', or '.xz' (otherwise no compression). If dict and compression
+ mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above,
+ other entries passed as additional compression options.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -3308,6 +3400,11 @@ class StataWriterUTF8(StataWriter117):
>>> writer = StataWriterUTF8('./data_file.dta', data)
>>> writer.write_file()
+ Directly write a zip file
+ >>> compression = {"method": "zip", "archive_name": "data_file.dta"}
+ >>> writer = StataWriterUTF8('./data_file.zip', data, compression=compression)
+ >>> writer.write_file()
+
Or with long strings stored in strl format
>>> data = pd.DataFrame([['ᴀ relatively long ŝtring'], [''], ['']],
@@ -3331,6 +3428,7 @@ def __init__(
variable_labels: Optional[Dict[Label, str]] = None,
convert_strl: Optional[Sequence[Label]] = None,
version: Optional[int] = None,
+ compression: Union[str, Mapping[str, str], None] = "infer",
):
if version is None:
version = 118 if data.shape[1] <= 32767 else 119
@@ -3352,6 +3450,7 @@ def __init__(
data_label=data_label,
variable_labels=variable_labels,
convert_strl=convert_strl,
+ compression=compression,
)
# Override version set in StataWriter117 init
self._dta_version = version
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index 783e06c9b7f2e..e670e0cdf2ade 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -1,10 +1,13 @@
+import bz2
import datetime as dt
from datetime import datetime
import gzip
import io
+import lzma
import os
import struct
import warnings
+import zipfile
import numpy as np
import pytest
@@ -1863,3 +1866,60 @@ def test_backward_compat(version, datapath):
expected = pd.read_stata(ref)
old_dta = pd.read_stata(old)
tm.assert_frame_equal(old_dta, expected, check_dtype=False)
+
+
+@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
+@pytest.mark.parametrize("use_dict", [True, False])
+@pytest.mark.parametrize("infer", [True, False])
+def test_compression(compression, version, use_dict, infer):
+ file_name = "dta_inferred_compression.dta"
+ if compression:
+ file_ext = "gz" if compression == "gzip" and not use_dict else compression
+ file_name += f".{file_ext}"
+ compression_arg = compression
+ if infer:
+ compression_arg = "infer"
+ if use_dict:
+ compression_arg = {"method": compression}
+
+ df = DataFrame(np.random.randn(10, 2), columns=list("AB"))
+ df.index.name = "index"
+ with tm.ensure_clean(file_name) as path:
+ df.to_stata(path, version=version, compression=compression_arg)
+ if compression == "gzip":
+ with gzip.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression == "zip":
+ with zipfile.ZipFile(path, "r") as comp:
+ fp = io.BytesIO(comp.read(comp.filelist[0]))
+ elif compression == "bz2":
+ with bz2.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression == "xz":
+ with lzma.open(path, "rb") as comp:
+ fp = io.BytesIO(comp.read())
+ elif compression is None:
+ fp = path
+ reread = read_stata(fp, index_col="index")
+ tm.assert_frame_equal(reread, df)
+
+
+@pytest.mark.parametrize("method", ["zip", "infer"])
+@pytest.mark.parametrize("file_ext", [None, "dta", "zip"])
+def test_compression_dict(method, file_ext):
+ file_name = f"test.{file_ext}"
+ archive_name = "test.dta"
+ df = DataFrame(np.random.randn(10, 2), columns=list("AB"))
+ df.index.name = "index"
+ with tm.ensure_clean(file_name) as path:
+ compression = {"method": method, "archive_name": archive_name}
+ df.to_stata(path, compression=compression)
+ if method == "zip" or file_ext == "zip":
+ zp = zipfile.ZipFile(path, "r")
+ assert len(zp.filelist) == 1
+ assert zp.filelist[0].filename == archive_name
+ fp = io.BytesIO(zp.read(zp.filelist[0]))
+ else:
+ fp = path
+ reread = read_stata(fp, index_col="index")
+ tm.assert_frame_equal(reread, df)
| Add standard compression optons to stata exporters
closes #26599
- [X] closes #26599
- [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/34013 | 2020-05-05T22:13:55Z | 2020-05-12T16:10:36Z | 2020-05-12T16:10:36Z | 2020-07-28T14:41:35Z |
BUG: groupby with as_index=False shouldn't modify grouping columns | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 4605c14643fa2..b69eda2f5e2b3 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -561,6 +561,53 @@ Assignment to multiple columns of a :class:`DataFrame` when some of the columns
df[['a', 'c']] = 1
df
+.. _whatsnew_110.api_breaking.groupby_consistency:
+
+Consistency across groupby reductions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Using :meth:`DataFrame.groupby` with ``as_index=True`` and the aggregation ``nunique`` would include the grouping column(s) in the columns of the result. Now the grouping column(s) only appear in the index, consistent with other reductions. (:issue:`32579`)
+
+.. ipython:: python
+
+ df = pd.DataFrame({"a": ["x", "x", "y", "y"], "b": [1, 1, 2, 3]})
+ df
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [3]: df.groupby("a", as_index=True).nunique()
+ Out[4]:
+ a b
+ a
+ x 1 1
+ y 1 2
+
+*New behavior*:
+
+.. ipython:: python
+
+ df.groupby("a", as_index=True).nunique()
+
+Using :meth:`DataFrame.groupby` with ``as_index=False`` and the function ``idxmax``, ``idxmin``, ``mad``, ``nunique``, ``sem``, ``skew``, or ``std`` would modify the grouping column. Now the grouping column remains unchanged, consistent with other reductions. (:issue:`21090`, :issue:`10355`)
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [3]: df.groupby("a", as_index=False).nunique()
+ Out[4]:
+ a b
+ 0 1 1
+ 1 1 2
+
+*New behavior*:
+
+.. ipython:: python
+
+ df.groupby("a", as_index=False).nunique()
+
.. _whatsnew_110.deprecations:
Deprecations
@@ -819,7 +866,6 @@ Groupby/resample/rolling
- Bug in :meth:`Series.groupby` would raise ``ValueError`` when grouping by :class:`PeriodIndex` level (:issue:`34010`)
- Bug in :meth:`GroupBy.agg`, :meth:`GroupBy.transform`, and :meth:`GroupBy.resample` where subclasses are not preserved (:issue:`28330`)
- Bug in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
-- Bug in :meth:`DataFrameGroupby.std` and :meth:`DataFrameGroupby.sem` would modify grouped-by columns when ``as_index=False`` (:issue:`10355`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 69b143febeea2..ea4b6f4e65341 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1265,7 +1265,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
v = values[0]
- if isinstance(v, (np.ndarray, Index, Series)):
+ if isinstance(v, (np.ndarray, Index, Series)) or not self.as_index:
if isinstance(v, Series):
applied_index = self._selected_obj._get_axis(self.axis)
all_indexed_same = all_indexes_same([x.index for x in values])
@@ -1341,6 +1341,11 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
result = self.obj._constructor(
stacked_values.T, index=v.index, columns=key_index
)
+ elif not self.as_index:
+ # We add grouping column below, so create a frame here
+ result = DataFrame(
+ values, index=key_index, columns=[self._selection]
+ )
else:
# GH#1738: values is list of arrays of unequal lengths
# fall through to the outer else clause
@@ -1358,6 +1363,9 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
else:
result = result._convert(datetime=True)
+ if not self.as_index:
+ self._insert_inaxis_grouper_inplace(result)
+
return self._reindex_output(result)
# values are not series or array-like but scalars
@@ -1700,9 +1708,11 @@ def _insert_inaxis_grouper_inplace(self, result):
),
)
)
-
+ columns = result.columns
for name, lev, in_axis in izip:
- if in_axis:
+ # GH #28549
+ # When using .apply(-), name will be in columns already
+ if in_axis and name not in columns:
result.insert(0, name, lev)
def _wrap_aggregated_output(
@@ -1852,11 +1862,11 @@ def nunique(self, dropna: bool = True):
5 ham 5 y
>>> df.groupby('id').nunique()
- id value1 value2
+ value1 value2
id
- egg 1 1 1
- ham 1 1 2
- spam 1 2 1
+ egg 1 1
+ ham 1 2
+ spam 2 1
Check for rows with the same id but conflicting values:
@@ -1867,37 +1877,37 @@ def nunique(self, dropna: bool = True):
4 ham 5 x
5 ham 5 y
"""
- obj = self._selected_obj
+ from pandas.core.reshape.concat import concat
- def groupby_series(obj, col=None):
- return SeriesGroupBy(obj, selection=col, grouper=self.grouper).nunique(
- dropna=dropna
- )
+ # TODO: this is duplicative of how GroupBy naturally works
+ # Try to consolidate with normal wrapping functions
- if isinstance(obj, Series):
- results = groupby_series(obj)
+ obj = self._obj_with_exclusions
+ axis_number = obj._get_axis_number(self.axis)
+ other_axis = int(not axis_number)
+ if axis_number == 0:
+ iter_func = obj.items
else:
- # TODO: this is duplicative of how GroupBy naturally works
- # Try to consolidate with normal wrapping functions
- from pandas.core.reshape.concat import concat
-
- axis_number = obj._get_axis_number(self.axis)
- other_axis = int(not axis_number)
- if axis_number == 0:
- iter_func = obj.items
- else:
- iter_func = obj.iterrows
+ iter_func = obj.iterrows
- results = [groupby_series(content, label) for label, content in iter_func()]
- results = concat(results, axis=1)
+ results = concat(
+ [
+ SeriesGroupBy(content, selection=label, grouper=self.grouper).nunique(
+ dropna
+ )
+ for label, content in iter_func()
+ ],
+ axis=1,
+ )
- if axis_number == 1:
- results = results.T
+ if axis_number == 1:
+ results = results.T
- results._get_axis(other_axis).names = obj._get_axis(other_axis).names
+ results._get_axis(other_axis).names = obj._get_axis(other_axis).names
if not self.as_index:
results.index = ibase.default_index(len(results))
+ self._insert_inaxis_grouper_inplace(results)
return results
boxplot = boxplot_frame_groupby
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 37f2376d68d55..9838cff9b34f9 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -35,7 +35,7 @@ class providing the base-class of operations.
from pandas._libs import Timestamp
import pandas._libs.groupby as libgroupby
-from pandas._typing import FrameOrSeries, Scalar
+from pandas._typing import F, FrameOrSeries, FrameOrSeriesUnion, Scalar
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc
@@ -735,11 +735,11 @@ def _make_wrapper(self, name):
# need to setup the selection
# as are not passed directly but in the grouper
- f = getattr(self._selected_obj, name)
+ f = getattr(self._obj_with_exclusions, name)
if not isinstance(f, types.MethodType):
return self.apply(lambda self: getattr(self, name))
- f = getattr(type(self._selected_obj), name)
+ f = getattr(type(self._obj_with_exclusions), name)
sig = inspect.signature(f)
def wrapper(*args, **kwargs):
@@ -762,7 +762,7 @@ def curried(x):
return self.apply(curried)
try:
- return self.apply(curried)
+ return self._python_apply_general(curried, self._obj_with_exclusions)
except TypeError as err:
if not re.search(
"reduction operation '.*' not allowed for this dtype", str(err)
@@ -853,7 +853,7 @@ def f(g):
# ignore SettingWithCopy here in case the user mutates
with option_context("mode.chained_assignment", None):
try:
- result = self._python_apply_general(f)
+ result = self._python_apply_general(f, self._selected_obj)
except TypeError:
# gh-20949
# try again, with .apply acting as a filtering
@@ -864,12 +864,29 @@ def f(g):
# on a string grouper column
with _group_selection_context(self):
- return self._python_apply_general(f)
+ return self._python_apply_general(f, self._selected_obj)
return result
- def _python_apply_general(self, f):
- keys, values, mutated = self.grouper.apply(f, self._selected_obj, self.axis)
+ def _python_apply_general(
+ self, f: F, data: FrameOrSeriesUnion
+ ) -> FrameOrSeriesUnion:
+ """
+ Apply function f in python space
+
+ Parameters
+ ----------
+ f : callable
+ Function to apply
+ data : Series or DataFrame
+ Data to apply f to
+
+ Returns
+ -------
+ Series or DataFrame
+ data after applying f
+ """
+ keys, values, mutated = self.grouper.apply(f, data, self.axis)
return self._wrap_applied_output(
keys, values, not_indexed_same=mutated or self.mutated
@@ -1067,7 +1084,7 @@ def _python_agg_general(
output[key] = maybe_cast_result(result, obj, numeric_only=True)
if len(output) == 0:
- return self._python_apply_general(f)
+ return self._python_apply_general(f, self._selected_obj)
if self.grouper._filter_empty_groups:
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 9d7bc749d6e89..9303a084f1e71 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -280,7 +280,7 @@ def test_non_cython_api():
result = g.mad()
tm.assert_frame_equal(result, expected)
- expected = DataFrame([[0.0, 0.0], [0, np.nan]], columns=["A", "B"], index=[0, 1])
+ expected = DataFrame([[1, 0.0], [3, np.nan]], columns=["A", "B"], index=[0, 1])
result = gni.mad()
tm.assert_frame_equal(result, expected)
@@ -573,28 +573,6 @@ def test_ops_general(op, targop):
tm.assert_frame_equal(result, expected)
-def test_ops_not_as_index(reduction_func):
- # GH 10355
- # Using as_index=False should not modify grouped column
-
- if reduction_func in ("nth", "ngroup", "size",):
- pytest.skip("Skip until behavior is determined (GH #5755)")
-
- if reduction_func in ("corrwith", "idxmax", "idxmin", "mad", "nunique", "skew",):
- pytest.xfail(
- "_GroupBy._python_apply_general incorrectly modifies grouping columns"
- )
-
- df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
- expected = getattr(df.groupby("a"), reduction_func)().reset_index()
-
- result = getattr(df.groupby("a", as_index=False), reduction_func)()
- tm.assert_frame_equal(result, expected)
-
- result = getattr(df.groupby("a", as_index=False)["b"], reduction_func)()
- tm.assert_frame_equal(result, expected)
-
-
def test_max_nan_bug():
raw = """,Date,app,File
-04-23,2013-04-23 00:00:00,,log080001.log
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index c88d16e34eab8..90c0d6bd183f2 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -658,6 +658,34 @@ def test_groupby_as_index_agg(df):
tm.assert_frame_equal(left, right)
+def test_ops_not_as_index(reduction_func):
+ # GH 10355, 21090
+ # Using as_index=False should not modify grouped column
+
+ if reduction_func in ("corrwith",):
+ pytest.skip("Test not applicable")
+
+ if reduction_func in ("nth", "ngroup", "size",):
+ pytest.skip("Skip until behavior is determined (GH #5755)")
+
+ df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"])
+ expected = getattr(df.groupby("a"), reduction_func)().reset_index()
+
+ g = df.groupby("a", as_index=False)
+
+ result = getattr(g, reduction_func)()
+ tm.assert_frame_equal(result, expected)
+
+ result = g.agg(reduction_func)
+ tm.assert_frame_equal(result, expected)
+
+ result = getattr(g["b"], reduction_func)()
+ tm.assert_frame_equal(result, expected)
+
+ result = g["b"].agg(reduction_func)
+ tm.assert_frame_equal(result, expected)
+
+
def test_as_index_series_return_frame(df):
grouped = df.groupby("A", as_index=False)
grouped2 = df.groupby(["A", "B"], as_index=False)
diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py
index 952443e0ad23b..1475b1ce2907c 100644
--- a/pandas/tests/groupby/test_nunique.py
+++ b/pandas/tests/groupby/test_nunique.py
@@ -25,7 +25,10 @@ def check_nunique(df, keys, as_index=True):
if not as_index:
right = right.reset_index(drop=True)
- tm.assert_series_equal(left, right, check_names=False)
+ if as_index:
+ tm.assert_series_equal(left, right, check_names=False)
+ else:
+ tm.assert_frame_equal(left, right, check_names=False)
tm.assert_frame_equal(df, original_df)
days = date_range("2015-08-23", periods=10)
@@ -56,13 +59,14 @@ def check_nunique(df, keys, as_index=True):
def test_nunique():
df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")})
- expected = DataFrame({"A": [1] * 3, "B": [1, 2, 1], "C": [1, 1, 2]})
+ expected = DataFrame({"A": list("abc"), "B": [1, 2, 1], "C": [1, 1, 2]})
result = df.groupby("A", as_index=False).nunique()
tm.assert_frame_equal(result, expected)
# as_index
expected.index = list("abc")
expected.index.name = "A"
+ expected = expected.drop(columns="A")
result = df.groupby("A").nunique()
tm.assert_frame_equal(result, expected)
@@ -71,7 +75,7 @@ def test_nunique():
tm.assert_frame_equal(result, expected)
# dropna
- expected = DataFrame({"A": [1] * 3, "B": [1] * 3, "C": [1] * 3}, index=list("abc"))
+ expected = DataFrame({"B": [1] * 3, "C": [1] * 3}, index=list("abc"))
expected.index.name = "A"
result = df.replace({"x": None}).groupby("A").nunique()
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py
index 8e387e9202ef6..6b33049a664de 100644
--- a/pandas/tests/groupby/test_whitelist.py
+++ b/pandas/tests/groupby/test_whitelist.py
@@ -406,7 +406,7 @@ def test_all_methods_categorized(mframe):
if new_names:
msg = f"""
There are uncatgeorized methods defined on the Grouper class:
-{names}.
+{new_names}.
Was a new method recently added?
| - [x] closes #32579
- [x] closes #21090
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This makes any groupby function that uses _GroupBy._make_wrapper to act on self._obj_with_exclusions rather than self._selected_obj, in parallel with the cython paths. Also similar to the cython paths, the grouping columns are added back onto the result in _wrap_applied_output. Similar remarks apply to nunique, which does not go through the _make_wrapper.
After finishing this, I found PR #29131. This PR does not change the behavior of calling apply() itself, only the previous code paths that would internally go through apply. Also, the change made there does not have any impact when as_index is False. | https://api.github.com/repos/pandas-dev/pandas/pulls/34012 | 2020-05-05T21:19:29Z | 2020-05-27T12:43:34Z | 2020-05-27T12:43:34Z | 2020-07-11T16:02:05Z |
REF: avoid importing pd.NA in tslibs | diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd
index b32492c1a83fc..090c5c5173280 100644
--- a/pandas/_libs/missing.pxd
+++ b/pandas/_libs/missing.pxd
@@ -6,6 +6,7 @@ cpdef ndarray[uint8_t] isnaobj(ndarray arr)
cdef bint is_null_datetime64(v)
cdef bint is_null_timedelta64(v)
+cdef bint checknull_with_nat_and_na(object obj)
cdef class C_NAType:
pass
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx
index 490abdf473319..62a8bfccaa432 100644
--- a/pandas/_libs/missing.pyx
+++ b/pandas/_libs/missing.pyx
@@ -279,6 +279,11 @@ cdef inline bint is_null_timedelta64(v):
return False
+cdef bint checknull_with_nat_and_na(object obj):
+ # See GH#32214
+ return checknull_with_nat(obj) or obj is C_NA
+
+
# -----------------------------------------------------------------------------
# Implementation of NA singleton
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 556cab565860c..e1205bb1f4820 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -51,8 +51,7 @@ from pandas._libs.tslibs.conversion cimport (
get_datetime64_nanos)
from pandas._libs.tslibs.nattype import nat_strings
-from pandas._libs.tslibs.nattype cimport (
- checknull_with_nat, NPY_NAT, c_NaT as NaT)
+from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT
from pandas._libs.tslibs.offsets cimport to_offset
@@ -64,6 +63,9 @@ from pandas._libs.tslibs.tzconversion cimport (
tz_convert_utc_to_tzlocal,
)
+# Note: this is the only non-tslibs intra-pandas dependency here
+from pandas._libs.missing cimport checknull_with_nat_and_na
+
cdef inline object create_datetime_from_ts(
int64_t value,
@@ -438,7 +440,7 @@ def array_with_unit_to_datetime(
for i in range(n):
val = values[i]
- if checknull_with_nat(val):
+ if checknull_with_nat_and_na(val):
iresult[i] = NPY_NAT
elif is_integer_object(val) or is_float_object(val):
@@ -505,7 +507,7 @@ def array_with_unit_to_datetime(
for i in range(n):
val = values[i]
- if checknull_with_nat(val):
+ if checknull_with_nat_and_na(val):
oresult[i] = <object>NaT
elif is_integer_object(val) or is_float_object(val):
@@ -602,7 +604,7 @@ cpdef array_to_datetime(
val = values[i]
try:
- if checknull_with_nat(val):
+ if checknull_with_nat_and_na(val):
iresult[i] = NPY_NAT
elif PyDateTime_Check(val):
@@ -812,7 +814,7 @@ cdef ignore_errors_out_of_bounds_fallback(ndarray[object] values):
val = values[i]
# set as nan except if its a NaT
- if checknull_with_nat(val):
+ if checknull_with_nat_and_na(val):
if isinstance(val, float):
oresult[i] = np.nan
else:
@@ -874,7 +876,7 @@ cdef array_to_datetime_object(
# 2) datetime strings, which we return as datetime.datetime
for i in range(n):
val = values[i]
- if checknull_with_nat(val) or PyDateTime_Check(val):
+ if checknull_with_nat_and_na(val) or PyDateTime_Check(val):
# GH 25978. No need to parse NaT-like or datetime-like vals
oresult[i] = val
elif isinstance(val, str):
diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx
index a45e10e8337a4..d0d03919f65ef 100644
--- a/pandas/_libs/tslibs/nattype.pyx
+++ b/pandas/_libs/tslibs/nattype.pyx
@@ -31,8 +31,6 @@ from pandas._libs.tslibs.np_datetime cimport (
)
cimport pandas._libs.tslibs.util as util
-from pandas._libs.missing cimport C_NA
-
# ----------------------------------------------------------------------
# Constants
@@ -809,7 +807,7 @@ cdef inline bint checknull_with_nat(object val):
"""
Utility to check if a value is a nat or not.
"""
- return val is None or util.is_nan(val) or val is c_NaT or val is C_NA
+ return val is None or util.is_nan(val) or val is c_NaT
cpdef bint is_null_datetimelike(object val, bint inat_is_null=True):
| The existing cimport of pd.NA into tslibs.nattype is a circular dependency (its not actually clear to me why it doesnt raise). I'm finding that its presence is making other refactoring around tslibs.offsets more difficult. This PR moves the import of pd.NA to tslib, breaking the circular dependency.
This _does_ change some behavior, but none that is tested, so we should discuss what places we want to recognize pd.NA. In particular, `pd.Timedelta(pd.NA)` returns `NaT` in master and raises `ValueError` in this PR. `pd.Timestamp(pd.NA)` and `pd.Period(pd.NA)` raise TypeError and ValueError, respectively, in both master and this PR.
cc @jorisvandenbossche what is your preferred behavior? | https://api.github.com/repos/pandas-dev/pandas/pulls/34009 | 2020-05-05T20:09:23Z | 2020-05-09T20:20:33Z | 2020-05-09T20:20:33Z | 2020-05-09T21:43:48Z |
CLN: avoid getattr checks in liboffsets | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 9fbe717fa8c2c..6005905ad59fd 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -32,6 +32,7 @@ from pandas._libs.tslibs.np_datetime cimport (
npy_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct)
from pandas._libs.tslibs.timezones import UTC
from pandas._libs.tslibs.tzconversion cimport tz_convert_single
+from pandas._libs.tslibs.c_timestamp cimport _Timestamp
# ---------------------------------------------------------------------
@@ -105,17 +106,18 @@ cdef to_offset(object obj):
return to_offset(obj)
-def as_datetime(obj):
- f = getattr(obj, 'to_pydatetime', None)
- if f is not None:
- obj = f()
+def as_datetime(obj: datetime) -> datetime:
+ if isinstance(obj, _Timestamp):
+ return obj.to_pydatetime()
return obj
-cpdef bint is_normalized(dt):
- if (dt.hour != 0 or dt.minute != 0 or dt.second != 0 or
- dt.microsecond != 0 or getattr(dt, 'nanosecond', 0) != 0):
+cpdef bint is_normalized(datetime dt):
+ if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0:
+ # Regardless of whether dt is datetime vs Timestamp
return False
+ if isinstance(dt, _Timestamp):
+ return dt.nanosecond == 0
return True
| https://api.github.com/repos/pandas-dev/pandas/pulls/34008 | 2020-05-05T19:13:30Z | 2020-05-06T23:06:48Z | 2020-05-06T23:06:48Z | 2020-05-07T00:39:07Z | |
CLN: avoid _typ checks in Period ops | diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index 878dbcfd99842..a64bf03b5c166 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1569,16 +1569,7 @@ cdef class _Period:
return PyObject_RichCompareBool(self.ordinal, other.ordinal, op)
elif other is NaT:
return _nat_scalar_rules[op]
- # index/series like
- elif hasattr(other, '_typ'):
- return NotImplemented
- else:
- if op == Py_EQ:
- return NotImplemented
- elif op == Py_NE:
- return NotImplemented
- raise TypeError(f"Cannot compare type {type(self).__name__} "
- f"with type {type(other).__name__}")
+ return NotImplemented
def __hash__(self):
return hash((self.ordinal, self.freqstr))
@@ -1654,13 +1645,7 @@ cdef class _Period:
raise IncompatibleFrequency(msg)
# GH 23915 - mul by base freq since __add__ is agnostic of n
return (self.ordinal - other.ordinal) * self.freq.base
- elif getattr(other, '_typ', None) == 'periodindex':
- # GH#21314 PeriodIndex - Period returns an object-index
- # of DateOffset objects, for which we cannot use __neg__
- # directly, so we have to apply it pointwise
- return other.__sub__(self).map(lambda x: -x)
- else: # pragma: no cover
- return NotImplemented
+ return NotImplemented
elif is_period_object(other):
if self is NaT:
return NaT
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 0e8bec331ea3f..3b3f5cb90bb31 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -153,9 +153,11 @@ def test_eq_integer_disallowed(self, other):
result = idx == other
tm.assert_numpy_array_equal(result, expected)
- msg = (
- r"(:?Invalid comparison between dtype=period\[D\] and .*)"
- r"|(:?Cannot compare type Period with type .*)"
+ msg = "|".join(
+ [
+ "not supported between instances of 'Period' and 'int'",
+ r"Invalid comparison between dtype=period\[D\] and ",
+ ]
)
with pytest.raises(TypeError, match=msg):
idx < other
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py
index 620fc1c006d93..01b61da099481 100644
--- a/pandas/tests/scalar/period/test_period.py
+++ b/pandas/tests/scalar/period/test_period.py
@@ -992,7 +992,8 @@ def test_comparison_invalid_type(self):
assert not jan == 1
assert jan != 1
- msg = "Cannot compare type Period with type int"
+ int_or_per = "'(Period|int)'"
+ msg = f"not supported between instances of {int_or_per} and {int_or_per}"
for left, right in [(jan, 1), (1, jan)]:
with pytest.raises(TypeError, match=msg):
| https://api.github.com/repos/pandas-dev/pandas/pulls/34007 | 2020-05-05T18:11:34Z | 2020-05-06T23:07:26Z | 2020-05-06T23:07:26Z | 2020-05-07T00:42:25Z | |
CLN: remove unused out-of-bounds handling | diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 5a8d0a0ec1670..6dd5b4b2fa798 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -265,7 +265,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit,
ts = <int64_t>ts
except OverflowError:
# GH#26651 re-raise as OutOfBoundsDatetime
- raise OutOfBoundsDatetime(ts)
+ raise OutOfBoundsDatetime(f"Out of bounds nanosecond timestamp {ts}")
if ts == NPY_NAT:
obj.value = NPY_NAT
else:
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index c1ab752bf9550..e1de9d1bcf832 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -8,7 +8,6 @@
from pandas._libs.tslibs import (
NaT,
- OutOfBoundsDatetime,
Period,
Timedelta,
Timestamp,
@@ -16,9 +15,7 @@
conversion,
delta_to_nanoseconds,
frequencies as libfrequencies,
- normalize_date,
offsets as liboffsets,
- timezones,
)
from pandas._libs.tslibs.offsets import (
ApplyTypeError,
@@ -76,73 +73,47 @@
"DateOffset",
]
-# convert to/from datetime/timestamp to allow invalid Timestamp ranges to
-# pass thru
-
-
-def as_timestamp(obj):
- if isinstance(obj, Timestamp):
- return obj
- try:
- return Timestamp(obj)
- except (OutOfBoundsDatetime):
- pass
- return obj
-
def apply_wraps(func):
@functools.wraps(func)
def wrapper(self, other):
if other is NaT:
return NaT
- elif isinstance(other, (timedelta, Tick, DateOffset)):
+ elif isinstance(other, (timedelta, DateOffset)):
# timedelta path
return func(self, other)
elif isinstance(other, (np.datetime64, datetime, date)):
- other = as_timestamp(other)
-
- tz = getattr(other, "tzinfo", None)
- nano = getattr(other, "nanosecond", 0)
-
- try:
- if self._adjust_dst and isinstance(other, Timestamp):
- other = other.tz_localize(None)
-
- result = func(self, other)
-
- if self._adjust_dst:
- result = conversion.localize_pydatetime(result, tz)
+ other = Timestamp(other)
+ else:
+ raise TypeError(other)
- result = Timestamp(result)
- if self.normalize:
- result = result.normalize()
+ tz = other.tzinfo
+ nano = other.nanosecond
- # nanosecond may be deleted depending on offset process
- if not self.normalize and nano != 0:
- if not isinstance(self, Nano) and result.nanosecond != nano:
- if result.tz is not None:
- # convert to UTC
- value = conversion.tz_convert_single(
- result.value, timezones.UTC, result.tz
- )
- else:
- value = result.value
- result = Timestamp(value + nano)
+ if self._adjust_dst:
+ other = other.tz_localize(None)
- if tz is not None and result.tzinfo is None:
- result = conversion.localize_pydatetime(result, tz)
+ result = func(self, other)
- except OutOfBoundsDatetime:
- result = func(self, as_datetime(other))
+ result = Timestamp(result)
+ if self._adjust_dst:
+ result = result.tz_localize(tz)
- if self.normalize:
- # normalize_date returns normal datetime
- result = normalize_date(result)
+ if self.normalize:
+ result = result.normalize()
- if tz is not None and result.tzinfo is None:
- result = conversion.localize_pydatetime(result, tz)
+ # nanosecond may be deleted depending on offset process
+ if not self.normalize and nano != 0:
+ if not isinstance(self, Nano) and result.nanosecond != nano:
+ if result.tz is not None:
+ # convert to UTC
+ value = result.tz_localize(None).value
+ else:
+ value = result.value
+ result = Timestamp(value + nano)
- result = Timestamp(result)
+ if tz is not None and result.tzinfo is None:
+ result = result.tz_localize(tz)
return result
@@ -290,7 +261,7 @@ def apply(self, other):
# bring tz back from UTC calculation
other = conversion.localize_pydatetime(other, tzinfo)
- return as_timestamp(other)
+ return Timestamp(other)
else:
return other + timedelta(self.n)
@@ -394,7 +365,7 @@ def rollback(self, dt):
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp.
"""
- dt = as_timestamp(dt)
+ dt = Timestamp(dt)
if not self.is_on_offset(dt):
dt = dt - type(self)(1, normalize=self.normalize, **self.kwds)
return dt
@@ -408,7 +379,7 @@ def rollforward(self, dt):
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp.
"""
- dt = as_timestamp(dt)
+ dt = Timestamp(dt)
if not self.is_on_offset(dt):
dt = dt + type(self)(1, normalize=self.normalize, **self.kwds)
return dt
@@ -2505,7 +2476,7 @@ def apply(self, other):
raise OverflowError
return result
elif isinstance(other, (datetime, np.datetime64, date)):
- return as_timestamp(other) + self
+ return Timestamp(other) + self
if isinstance(other, timedelta):
return other + self.delta
| We only have one test that goes through the OOB handling code, and that re-raises within the OOB handling. We're better off being strict here like everywhere else rather than having spotty support. | https://api.github.com/repos/pandas-dev/pandas/pulls/34006 | 2020-05-05T16:26:29Z | 2020-05-05T22:24:38Z | 2020-05-05T22:24:38Z | 2020-05-05T22:40:51Z |
release note for #33102 | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 294b2c3512623..48680d2b698a8 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -18,6 +18,7 @@ Fixed regressions
- Bug where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
+- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
-
| xref #33157 | https://api.github.com/repos/pandas-dev/pandas/pulls/34005 | 2020-05-05T16:01:51Z | 2020-05-06T09:14:08Z | 2020-05-06T09:14:08Z | 2020-05-06T09:14:14Z |
Backport PR #33292 on branch 1.0.x (REGR: Fix bug when replacing cate… | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 8eb6b32669d60..1ce3ba5f088e7 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -17,6 +17,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
+- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
-
.. _whatsnew_104.bug_fixes:
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index d8a2fbdd58382..756896279054c 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2459,6 +2459,8 @@ def replace(self, to_replace, value, inplace: bool = False):
# other cases, like if both to_replace and value are list-like or if
# to_replace is a dict, are handled separately in NDFrame
for replace_value, new_value in replace_dict.items():
+ if new_value == replace_value:
+ continue
if replace_value in cat.categories:
if isna(new_value):
cat.remove_categories(replace_value, inplace=True)
diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py
index 835aa87a7c21b..50ad27ce3c2c5 100644
--- a/pandas/tests/arrays/categorical/test_algos.py
+++ b/pandas/tests/arrays/categorical/test_algos.py
@@ -64,6 +64,8 @@ def test_isin_cats():
[
("b", "c", ["a", "c"], "Categorical.categories are different"),
("c", "d", ["a", "b"], None),
+ # https://github.com/pandas-dev/pandas/issues/33288
+ ("a", "a", ["a", "b"], None),
("b", None, ["a", None], "Categorical.categories length are different"),
],
)
| …gorical value with self)
xref #33292
fixes regression in 1.0.0 #33288 | https://api.github.com/repos/pandas-dev/pandas/pulls/34004 | 2020-05-05T15:41:40Z | 2020-05-05T19:30:13Z | 2020-05-05T19:30:13Z | 2020-05-05T19:30:18Z |
Backport PR #32870 on branch 1.0.x (DOC: Remove latest whatsnew from … | diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template
index 5428239ed2e27..4aba8f709fba0 100644
--- a/doc/source/index.rst.template
+++ b/doc/source/index.rst.template
@@ -119,7 +119,6 @@ programming language.
:titlesonly:
{% endif %}
{% if not single_doc %}
- What's New in 1.0.1 <whatsnew/v1.0.1>
getting_started/index
user_guide/index
{% endif -%}
| …header)
xref #32870 | https://api.github.com/repos/pandas-dev/pandas/pulls/34003 | 2020-05-05T15:26:06Z | 2020-05-05T19:30:50Z | 2020-05-05T19:30:50Z | 2020-05-05T19:30:54Z |
Backport PR #33629 on branch 1.0.x (BUG: Fix Categorical use_inf_as_n… | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index ed4a7ffc44441..2d1fe1756ee8b 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Bug where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
-
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index fb579f2f58a57..269f73153edfa 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -269,10 +269,18 @@ def _isna_ndarraylike(obj):
def _isna_ndarraylike_old(obj):
+ is_extension = is_extension_array_dtype(obj)
+
values = getattr(obj, "values", obj)
dtype = values.dtype
- if is_string_dtype(dtype):
+ if is_extension:
+ if isinstance(obj, (ABCIndexClass, ABCSeries)):
+ values = obj._values
+ else:
+ values = obj
+ result = values.isna() | (values == -np.inf) | (values == np.inf)
+ elif is_string_dtype(dtype):
# Working around NumPy ticket 1542
shape = values.shape
diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py
index 8889f45a84237..19ab6d00ba10d 100644
--- a/pandas/tests/arrays/categorical/test_missing.py
+++ b/pandas/tests/arrays/categorical/test_missing.py
@@ -5,7 +5,8 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas import Categorical, Index, Series, isna
+import pandas as pd
+from pandas import Categorical, DataFrame, Index, Series, isna
import pandas._testing as tm
@@ -82,3 +83,53 @@ def test_fillna_iterable_category(self, named):
expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)])
tm.assert_categorical_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values, expected",
+ [
+ ([1, 2, 3], np.array([False, False, False])),
+ ([1, 2, np.nan], np.array([False, False, True])),
+ ([1, 2, np.inf], np.array([False, False, True])),
+ ([1, 2, pd.NA], np.array([False, False, True])),
+ ],
+ )
+ def test_use_inf_as_na(self, values, expected):
+ # https://github.com/pandas-dev/pandas/issues/33594
+ with pd.option_context("mode.use_inf_as_na", True):
+ cat = Categorical(values)
+ result = cat.isna()
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = Series(cat).isna()
+ expected = Series(expected)
+ tm.assert_series_equal(result, expected)
+
+ result = DataFrame(cat).isna()
+ expected = DataFrame(expected)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "values, expected",
+ [
+ ([1, 2, 3], np.array([False, False, False])),
+ ([1, 2, np.nan], np.array([False, False, True])),
+ ([1, 2, np.inf], np.array([False, False, True])),
+ ([1, 2, pd.NA], np.array([False, False, True])),
+ ],
+ )
+ def test_use_inf_as_na_outside_context(self, values, expected):
+ # https://github.com/pandas-dev/pandas/issues/33594
+ # Using isna directly for Categorical will fail in general here
+ cat = Categorical(values)
+
+ with pd.option_context("mode.use_inf_as_na", True):
+ result = pd.isna(cat)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = pd.isna(Series(cat))
+ expected = Series(expected)
+ tm.assert_series_equal(result, expected)
+
+ result = pd.isna(DataFrame(cat))
+ expected = DataFrame(expected)
+ tm.assert_frame_equal(result, expected)
| …a bug)
xref #33629
fixed regression in 1.0.0 (#33594)
# NOTE: code changes in #33629 not really suitable for backport. | https://api.github.com/repos/pandas-dev/pandas/pulls/34001 | 2020-05-05T14:21:33Z | 2020-05-05T19:31:50Z | 2020-05-05T19:31:50Z | 2020-05-05T19:31:54Z |
Backport PR #33761 on branch 1.0.x (REGR: fix DataFrame reduction wit… | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index ed4a7ffc44441..8eb6b32669d60 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -16,6 +16,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
+- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
-
.. _whatsnew_104.bug_fixes:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 819d341d2d5b4..94f70f7ea2165 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7891,9 +7891,15 @@ def _get_data(axis_matters):
out_dtype = "bool" if filter_type == "bool" else None
+ def blk_func(values):
+ 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
- res = df._data.reduce(op, axis=1, skipna=skipna, **kwds)
+ res = df._data.reduce(blk_func)
assert isinstance(res, dict)
if len(res):
assert len(res) == max(list(res.keys())) + 1, res.keys()
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 25b2997eb088f..8e1c3effb6cfc 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -891,6 +891,20 @@ def test_mean_datetimelike_numeric_only_false(self):
)
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="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)
| …h EA columns and numeric_only=True)
xref #33761
fixes regression in 1.0.0 (#33256) | https://api.github.com/repos/pandas-dev/pandas/pulls/34000 | 2020-05-05T13:14:40Z | 2020-05-05T14:39:25Z | 2020-05-05T14:39:25Z | 2020-05-05T14:39:31Z |
Backport PR #33462 on branch 1.0.x (BUG: None converted to NaN after … | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index fa3ac27eba577..ed4a7ffc44441 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -15,7 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
--
+- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
-
.. _whatsnew_104.bug_fixes:
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 3bfbd1a88650a..53c37c8cc8190 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -892,7 +892,9 @@ def group_last(rank_t[:, :] out,
for j in range(K):
val = values[i, j]
- if not checknull(val):
+ # None should not be treated like other NA-like
+ # so that it won't be converted to nan
+ if not checknull(val) or val is None:
# NB: use _treat_as_na here once
# conditional-nogil is available.
nobs[lab, j] += 1
@@ -983,7 +985,9 @@ def group_nth(rank_t[:, :] out,
for j in range(K):
val = values[i, j]
- if not checknull(val):
+ # None should not be treated like other NA-like
+ # so that it won't be converted to nan
+ if not checknull(val) or val is None:
# NB: use _treat_as_na here once
# conditional-nogil is available.
nobs[lab, j] += 1
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index b1476f1059d84..7b2e3f7a7e06a 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -94,6 +94,17 @@ def test_nth_with_na_object(index, nulls_fixture):
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize("method", ["first", "last"])
+def test_first_last_with_None(method):
+ # https://github.com/pandas-dev/pandas/issues/32800
+ # None should be preserved as object dtype
+ df = pd.DataFrame.from_dict({"id": ["a"], "value": [None]})
+ groups = df.groupby("id", as_index=False)
+ result = getattr(groups, method)()
+
+ tm.assert_frame_equal(result, df)
+
+
def test_first_last_nth_dtypes(df_mixed_floats):
df = df_mixed_floats.copy()
| …groupby first and last)
xref #33462
fixes regression in 1.0.2 (#32800) | https://api.github.com/repos/pandas-dev/pandas/pulls/33998 | 2020-05-05T12:16:39Z | 2020-05-05T12:55:16Z | 2020-05-05T12:55:16Z | 2020-05-05T12:55:24Z |
Backport PR #33954 on branch 1.0.x (DOC: update conf.py to use new numpy doc url) | diff --git a/doc/source/conf.py b/doc/source/conf.py
index 5ea76c2f9c39f..e8d825a509be9 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -408,7 +408,7 @@
intersphinx_mapping = {
"dateutil": ("https://dateutil.readthedocs.io/en/latest/", None),
"matplotlib": ("https://matplotlib.org/", None),
- "numpy": ("https://docs.scipy.org/doc/numpy/", None),
+ "numpy": ("https://numpy.org/doc/stable/", None),
"pandas-gbq": ("https://pandas-gbq.readthedocs.io/en/latest/", None),
"py": ("https://pylib.readthedocs.io/en/latest/", None),
"python": ("https://docs.python.org/3/", None),
| Backport PR #33954: DOC: update conf.py to use new numpy doc url | https://api.github.com/repos/pandas-dev/pandas/pulls/33996 | 2020-05-05T11:30:04Z | 2020-05-05T12:27:15Z | 2020-05-05T12:27:15Z | 2020-05-05T12:27:15Z |
BLD: recursive inclusion of DLLs in package data (#33246) | diff --git a/setup.py b/setup.py
index c33ce063cb4d9..e29f6fcd31bc8 100755
--- a/setup.py
+++ b/setup.py
@@ -753,7 +753,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
maintainer=AUTHOR,
version=versioneer.get_version(),
packages=find_packages(include=["pandas", "pandas.*"]),
- package_data={"": ["templates/*", "_libs/*.dll"]},
+ package_data={"": ["templates/*", "_libs/**/*.dll"]},
ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
maintainer_email=EMAIL,
description=DESCRIPTION,
| xref #33246 | https://api.github.com/repos/pandas-dev/pandas/pulls/33995 | 2020-05-05T10:49:44Z | 2020-05-05T11:27:29Z | 2020-05-05T11:27:29Z | 2020-05-05T11:27:41Z |
CI/DEP: Use numba.extending.is_jitted for numba version > 0.49.0 | diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py
index 127957943d2ff..d6f28c9005b9e 100644
--- a/pandas/core/window/numba_.py
+++ b/pandas/core/window/numba_.py
@@ -1,3 +1,4 @@
+from distutils.version import LooseVersion
import types
from typing import Any, Callable, Dict, Optional, Tuple
@@ -42,7 +43,12 @@ def make_rolling_apply(
else:
loop_range = range
- if isinstance(func, numba.targets.registry.CPUDispatcher):
+ if LooseVersion(numba.__version__) >= LooseVersion("0.49.0"):
+ is_jitted = numba.extending.is_jitted(func)
+ else:
+ is_jitted = isinstance(func, numba.targets.registry.CPUDispatcher)
+
+ if is_jitted:
# Don't jit a user passed jitted function
numba_func = func
else:
| xref #33687 | https://api.github.com/repos/pandas-dev/pandas/pulls/33994 | 2020-05-05T10:10:31Z | 2020-05-05T10:38:57Z | 2020-05-05T10:38:57Z | 2020-05-05T10:39:05Z |
Backport PR #33241 on branch 1.0.x (tostring->tobytes) | diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx
index 73201e75c3c88..e841ff7819347 100644
--- a/pandas/_libs/writers.pyx
+++ b/pandas/_libs/writers.pyx
@@ -107,7 +107,7 @@ def convert_json_to_lines(arr: object) -> str:
if not in_quotes:
num_open_brackets_seen -= 1
- return narr.tostring().decode('utf-8')
+ return narr.tobytes().decode('utf-8')
# stata, pytables
diff --git a/pandas/io/sas/sas.pyx b/pandas/io/sas/sas.pyx
index bb5bce96bc64b..2a6a7089d77fb 100644
--- a/pandas/io/sas/sas.pyx
+++ b/pandas/io/sas/sas.pyx
@@ -436,7 +436,7 @@ cdef class Parser:
elif column_types[j] == column_type_string:
# string
string_chunk[js, current_row] = np.array(source[start:(
- start + lngt)]).tostring().rstrip(b"\x00 ")
+ start + lngt)]).tobytes().rstrip(b"\x00 ")
js += 1
self.current_row_on_page_index += 1
| Backport PR #33241: tostring->tobytes | https://api.github.com/repos/pandas-dev/pandas/pulls/33993 | 2020-05-05T09:10:10Z | 2020-05-05T09:42:56Z | 2020-05-05T09:42:56Z | 2020-05-05T09:42:56Z |
CI: test_unsupported_other fails on pyarrow 0.17 | diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 0038df78dd866..23b51e718aa8c 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -102,8 +102,8 @@ def test_read_columns(self):
def test_unsupported_other(self):
- # period
- df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)})
+ # mixed python objects
+ df = pd.DataFrame({"a": ["a", 1, 2.0]})
# Some versions raise ValueError, others raise ArrowInvalid.
self.check_error_on_write(df, Exception)
| xref https://github.com/pandas-dev/pandas/issues/33300#issuecomment-623690451, https://github.com/pandas-dev/pandas/pull/33422#discussion_r406240082 | https://api.github.com/repos/pandas-dev/pandas/pulls/33990 | 2020-05-05T08:31:25Z | 2020-05-05T09:43:36Z | 2020-05-05T09:43:36Z | 2020-05-05T09:43:56Z |
DOC: Add plotting examples and fix broken examples | diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index 30c5ba0ed94b6..594b95d1937ea 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -117,8 +117,12 @@ def scatter_matrix(
Examples
--------
- >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
- >>> scatter_matrix(df, alpha=0.2)
+
+ .. plot::
+ :context: close-figs
+
+ >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
+ >>> pd.plotting.scatter_matrix(df, alpha=0.2)
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.scatter_matrix(
@@ -179,24 +183,31 @@ def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
Examples
--------
+
.. plot::
:context: close-figs
- >>> df = pd.DataFrame({
- ... 'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6,
- ... 6.7, 4.6],
- ... 'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2,
- ... 3.3, 3.6],
- ... 'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4,
- ... 5.7, 1.0],
- ... 'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2,
- ... 2.1, 0.2],
- ... 'Category': ['virginica', 'virginica', 'setosa',
- ... 'virginica', 'virginica', 'versicolor',
- ... 'versicolor', 'setosa', 'virginica',
- ... 'setosa']
- ... })
- >>> rad_viz = pd.plotting.radviz(df, 'Category') # doctest: +SKIP
+ >>> df = pd.DataFrame(
+ ... {
+ ... 'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6],
+ ... 'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6],
+ ... 'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0],
+ ... 'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2],
+ ... 'Category': [
+ ... 'virginica',
+ ... 'virginica',
+ ... 'setosa',
+ ... 'virginica',
+ ... 'virginica',
+ ... 'versicolor',
+ ... 'versicolor',
+ ... 'setosa',
+ ... 'virginica',
+ ... 'setosa'
+ ... ]
+ ... }
+ ... )
+ >>> pd.plotting.radviz(df, 'Category')
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.radviz(
@@ -243,6 +254,18 @@ def andrews_curves(
Returns
-------
class:`matplotlip.axis.Axes`
+
+ Examples
+ --------
+
+ .. plot::
+ :context: close-figs
+
+ >>> df = pd.read_csv(
+ ... 'https://raw.github.com/pandas-dev/'
+ ... 'pandas/master/pandas/tests/data/iris.csv'
+ ... )
+ >>> pd.plotting.andrews_curves(df, 'Name')
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.andrews_curves(
@@ -298,10 +321,10 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
This example draws a basic bootstap plot for a Series.
.. plot::
- :context: close-figs
+ :context: close-figs
- >>> s = pd.Series(np.random.uniform(size=100))
- >>> fig = pd.plotting.bootstrap_plot(s) # doctest: +SKIP
+ >>> s = pd.Series(np.random.uniform(size=100))
+ >>> pd.plotting.bootstrap_plot(s)
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.bootstrap_plot(
@@ -358,13 +381,17 @@ def parallel_coordinates(
Examples
--------
- >>> from matplotlib import pyplot as plt
- >>> df = pd.read_csv('https://raw.github.com/pandas-dev/pandas/master'
- '/pandas/tests/data/iris.csv')
- >>> pd.plotting.parallel_coordinates(
- df, 'Name',
- color=('#556270', '#4ECDC4', '#C7F464'))
- >>> plt.show()
+
+ .. plot::
+ :context: close-figs
+
+ >>> df = pd.read_csv(
+ ... 'https://raw.github.com/pandas-dev/'
+ ... 'pandas/master/pandas/tests/data/iris.csv'
+ ... )
+ >>> pd.plotting.parallel_coordinates(
+ ... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464')
+ ... )
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.parallel_coordinates(
@@ -398,6 +425,28 @@ def lag_plot(series, lag=1, ax=None, **kwds):
Returns
-------
class:`matplotlib.axis.Axes`
+
+ Examples
+ --------
+
+ Lag plots are most commonly used to look for patterns in time series data.
+
+ Given the following time series
+
+ .. plot::
+ :context: close-figs
+
+ >>> np.random.seed(5)
+ >>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
+ >>> s = pd.Series(x)
+ >>> s.plot()
+
+ A lag plot with ``lag=1`` returns
+
+ .. plot::
+ :context: close-figs
+
+ >>> pd.plotting.lag_plot(s, lag=1)
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds)
@@ -417,6 +466,20 @@ def autocorrelation_plot(series, ax=None, **kwargs):
Returns
-------
class:`matplotlib.axis.Axes`
+
+ Examples
+ --------
+
+ The horizontal lines in the plot correspond to 95% and 99% confidence bands.
+
+ The dashed line is 99% confidence band.
+
+ .. plot::
+ :context: close-figs
+
+ >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
+ >>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
+ >>> pd.plotting.autocorrelation_plot(s)
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs)
| This PR improves the `pandas.plotting._misc.py` module docs by:
1. Adding example plots where they were missing from docstrings.
2. Fixing examples that were not formatted to render with
```
.. plot::
:context: close-figs
```
3. Simplifying the syntax of some oddly-written examples.
In some cases, I replicated the examples found in the [User Guide](https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html#plotting-tools). | https://api.github.com/repos/pandas-dev/pandas/pulls/33989 | 2020-05-05T08:24:00Z | 2020-05-06T07:49:46Z | 2020-05-06T07:49:46Z | 2020-05-06T07:49:55Z |
BUG: fix memory_usage method with deep of StringArray | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index c3396a73f62ed..816ef4e5c9eb6 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -758,6 +758,7 @@ ExtensionArray
- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
- Fixed bug in :class:`Series` construction with EA dtype and index but no data or scalar data fails (:issue:`26469`)
- Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`).
+- Fixed bug where :meth:`StringArray.memory_usage` was not implemented (:issue:`33963`)
Other
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 51bbe182a002b..537b1cf3dd439 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -292,6 +292,12 @@ def value_counts(self, dropna=False):
return value_counts(self._ndarray, dropna=dropna).astype("Int64")
+ def memory_usage(self, deep=False):
+ result = self._ndarray.nbytes
+ if deep:
+ return result + lib.memory_usage_of_objects(self._ndarray)
+ return result
+
# Override parent because we have different return types.
@classmethod
def _create_arithmetic_method(cls, op):
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index eb89798a1ad96..b681abf03a2b3 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -303,3 +303,10 @@ def test_value_counts_na():
result = arr.value_counts(dropna=True)
expected = pd.Series([2, 1], index=["a", "b"], dtype="Int64")
tm.assert_series_equal(result, expected)
+
+
+def test_memory_usage():
+ # GH 33963
+ series = pd.Series(["a", "b", "c"], dtype="string")
+
+ assert 0 < series.nbytes <= series.memory_usage() < series.memory_usage(deep=True)
| - [ ] closes #33963
- [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/33985 | 2020-05-05T02:16:20Z | 2020-05-05T14:18:59Z | 2020-05-05T14:18:58Z | 2020-05-05T14:33:28Z |
BUG: Fix Series.update ExtensionArray issue | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 816ef4e5c9eb6..9c424f70b1ee0 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -758,6 +758,7 @@ ExtensionArray
- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
- Fixed bug in :class:`Series` construction with EA dtype and index but no data or scalar data fails (:issue:`26469`)
- Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`).
+- Fixed bug where :meth:`Series.update` would raise a ``ValueError`` for ``ExtensionArray`` dtypes with missing values (:issue:`33980`)
- Fixed bug where :meth:`StringArray.memory_usage` was not implemented (:issue:`33963`)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index d028d840448ea..e4dcffae45f67 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1599,7 +1599,7 @@ def putmask(
new_values = self.values if inplace else self.values.copy()
- if isinstance(new, np.ndarray) and len(new) == len(mask):
+ if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask):
new = new[mask]
mask = _safe_reshape(mask, new_values.shape)
diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index 98959599569a9..9cb6d8f81fff7 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -74,3 +74,27 @@ def test_update_from_non_series(self, series, other, expected):
# GH 33215
series.update(other)
tm.assert_series_equal(series, expected)
+
+ @pytest.mark.parametrize(
+ "result, target, expected",
+ [
+ (
+ Series(["a", None], dtype="string"),
+ Series([None, "b"], dtype="string"),
+ Series(["a", "b"], dtype="string"),
+ ),
+ (
+ Series([1, None], dtype="Int64"),
+ Series([None, 2], dtype="Int64"),
+ Series([1, 2], dtype="Int64"),
+ ),
+ (
+ Series([True, None], dtype="boolean"),
+ Series([None, False], dtype="boolean"),
+ Series([True, False], dtype="boolean"),
+ ),
+ ],
+ )
+ def test_update_extension_array_series(self, result, target, expected):
+ result.update(target)
+ tm.assert_series_equal(result, expected)
| - [x] closes #33980
- [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/33984 | 2020-05-05T00:07:40Z | 2020-05-05T16:27:25Z | 2020-05-05T16:27:25Z | 2020-05-30T16:30:29Z |
BUG: Use args and kwargs in Rolling.apply | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 57dad5a080358..5cb4bf0ef6ef4 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -814,6 +814,8 @@ Groupby/resample/rolling
- 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`)
- Bug in :meth:`GroupBy.agg`, :meth:`GroupBy.transform`, and :meth:`GroupBy.resample` where subclasses are not preserved (:issue:`28330`)
+- Bug in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
+
Reshaping
^^^^^^^^^
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 166ab13344816..660fca61fd21c 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -1302,6 +1302,8 @@ def apply(
use_numba_cache=engine == "numba",
raw=raw,
original_func=func,
+ args=args,
+ kwargs=kwargs,
)
def _generate_cython_apply_func(self, args, kwargs, raw, offset, func):
diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py
index 34cf0a3054889..bc38634da8941 100644
--- a/pandas/tests/window/test_apply.py
+++ b/pandas/tests/window/test_apply.py
@@ -4,7 +4,7 @@
from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, Timestamp, date_range
+from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range
import pandas._testing as tm
@@ -139,3 +139,28 @@ def test_invalid_kwargs_nopython():
Series(range(1)).rolling(1).apply(
lambda x: x, kwargs={"a": 1}, engine="numba", raw=True
)
+
+
+@pytest.mark.parametrize("args_kwargs", [[None, {"par": 10}], [(10,), None]])
+def test_rolling_apply_args_kwargs(args_kwargs):
+ # GH 33433
+ def foo(x, par):
+ return np.sum(x + par)
+
+ df = DataFrame({"gr": [1, 1], "a": [1, 2]})
+
+ idx = Index(["gr", "a"])
+ expected = DataFrame([[11.0, 11.0], [11.0, 12.0]], columns=idx)
+
+ result = df.rolling(1).apply(foo, args=args_kwargs[0], kwargs=args_kwargs[1])
+ tm.assert_frame_equal(result, expected)
+
+ result = df.rolling(1).apply(foo, args=(10,))
+
+ midx = MultiIndex.from_tuples([(1, 0), (1, 1)], names=["gr", None])
+ expected = Series([11.0, 12.0], index=midx, name="a")
+
+ gb_rolling = df.groupby("gr")["a"].rolling(1)
+
+ result = gb_rolling.apply(foo, args=args_kwargs[0], kwargs=args_kwargs[1])
+ tm.assert_series_equal(result, expected)
| - [x] closes #33433
- [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/33983 | 2020-05-05T00:02:04Z | 2020-05-15T14:11:40Z | 2020-05-15T14:11:39Z | 2020-05-15T20:28:12Z |
BUG: Handling columns from index_col in _is_potential_multi_index | diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index aca2f9f5ac5bb..c54e264faedd2 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -10,7 +10,7 @@
import re
import sys
from textwrap import fill
-from typing import Any, Dict, Iterable, List, Set
+from typing import Any, Dict, Iterable, List, Optional, Sequence, Set
import warnings
import numpy as np
@@ -20,7 +20,7 @@
import pandas._libs.parsers as parsers
from pandas._libs.parsers import STR_NA_VALUES
from pandas._libs.tslibs import parsing
-from pandas._typing import FilePathOrBuffer
+from pandas._typing import FilePathOrBuffer, Union
from pandas.errors import (
AbstractMethodError,
EmptyDataError,
@@ -1168,7 +1168,9 @@ def _is_index_col(col):
return col is not None and col is not False
-def _is_potential_multi_index(columns):
+def _is_potential_multi_index(
+ columns, index_col: Optional[Union[bool, Sequence[int]]] = None
+):
"""
Check whether or not the `columns` parameter
could be converted into a MultiIndex.
@@ -1177,15 +1179,20 @@ def _is_potential_multi_index(columns):
----------
columns : array-like
Object which may or may not be convertible into a MultiIndex
+ index_col : None, bool or list, optional
+ Column or columns to use as the (possibly hierarchical) index
Returns
-------
boolean : Whether or not columns could become a MultiIndex
"""
+ if index_col is None or isinstance(index_col, bool):
+ index_col = []
+
return (
len(columns)
and not isinstance(columns, MultiIndex)
- and all(isinstance(c, tuple) for c in columns)
+ and all(isinstance(c, tuple) for c in columns if c not in list(index_col))
)
@@ -1570,7 +1577,7 @@ def _maybe_dedup_names(self, names):
if self.mangle_dupe_cols:
names = list(names) # so we can index
counts = defaultdict(int)
- is_potential_mi = _is_potential_multi_index(names)
+ is_potential_mi = _is_potential_multi_index(names, self.index_col)
for i, col in enumerate(names):
cur_count = counts[col]
diff --git a/pandas/tests/io/data/excel/df_empty.xlsx b/pandas/tests/io/data/excel/df_empty.xlsx
new file mode 100644
index 0000000000000..d65a92b10e293
Binary files /dev/null and b/pandas/tests/io/data/excel/df_empty.xlsx differ
diff --git a/pandas/tests/io/data/excel/df_equals.xlsx b/pandas/tests/io/data/excel/df_equals.xlsx
new file mode 100644
index 0000000000000..d65a92b10e293
Binary files /dev/null and b/pandas/tests/io/data/excel/df_equals.xlsx differ
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 99447c03e89af..5401c4bea79f4 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -1084,3 +1084,16 @@ def test_excel_high_surrogate(self, engine):
# should not produce a segmentation violation
actual = pd.read_excel("high_surrogate.xlsx")
tm.assert_frame_equal(expected, actual)
+
+ @pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"])
+ def test_header_with_index_col(self, engine, filename):
+ # GH 33476
+ idx = pd.Index(["Z"], name="I2")
+ cols = pd.MultiIndex.from_tuples(
+ [("A", "B"), ("A", "B.1")], names=["I11", "I12"]
+ )
+ expected = pd.DataFrame([[1, 3]], index=idx, columns=cols, dtype="int64")
+ result = pd.read_excel(
+ filename, sheet_name="Sheet1", index_col=0, header=[0, 1]
+ )
+ tm.assert_frame_equal(expected, result)
diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py
index f67a658cadfa2..9f425168540ba 100644
--- a/pandas/tests/io/parser/test_index_col.py
+++ b/pandas/tests/io/parser/test_index_col.py
@@ -184,3 +184,26 @@ def test_no_multi_index_level_names_empty(all_parsers):
expected.to_csv(path)
result = parser.read_csv(path, index_col=[0, 1, 2])
tm.assert_frame_equal(result, expected)
+
+
+def test_header_with_index_col(all_parsers):
+ # GH 33476
+ parser = all_parsers
+ data = """
+I11,A,A
+I12,B,B
+I2,1,3
+"""
+ midx = MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"])
+ idx = Index(["I2"])
+ expected = DataFrame([[1, 3]], index=idx, columns=midx)
+
+ result = parser.read_csv(StringIO(data), index_col=0, header=[0, 1])
+ tm.assert_frame_equal(result, expected)
+
+ col_idx = Index(["A", "A.1"])
+ idx = Index(["I12", "I2"], name="I11")
+ expected = DataFrame([["B", "B"], ["1", "3"]], index=idx, columns=col_idx)
+
+ result = parser.read_csv(StringIO(data), index_col="I11", header=0)
+ tm.assert_frame_equal(result, expected)
| - [x] closes #33476
- [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/33982 | 2020-05-04T22:51:16Z | 2020-06-04T21:56:55Z | 2020-06-04T21:56:55Z | 2020-06-26T07:19:51Z |
PERF: make _Tick into a cdef class | diff --git a/pandas/_libs/tslibs/offsets.pxd b/pandas/_libs/tslibs/offsets.pxd
index 5a553be537e52..e75cd8bdf1baf 100644
--- a/pandas/_libs/tslibs/offsets.pxd
+++ b/pandas/_libs/tslibs/offsets.pxd
@@ -1 +1,3 @@
cdef to_offset(object obj)
+cdef bint is_offset_object(object obj)
+cdef bint is_tick_object(object obj)
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 3dfaa36888f62..9fbe717fa8c2c 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -86,6 +86,14 @@ for _d in DAYS:
# ---------------------------------------------------------------------
# Misc Helpers
+cdef bint is_offset_object(object obj):
+ return isinstance(obj, _BaseOffset)
+
+
+cdef bint is_tick_object(object obj):
+ return isinstance(obj, _Tick)
+
+
cdef to_offset(object obj):
"""
Wrap pandas.tseries.frequencies.to_offset to keep centralize runtime
@@ -608,7 +616,7 @@ class BaseOffset(_BaseOffset):
return -self + other
-class _Tick:
+cdef class _Tick:
"""
dummy class to mix into tseries.offsets.Tick so that in tslibs.period we
can do isinstance checks on _Tick and avoid importing tseries.offsets
@@ -618,12 +626,18 @@ class _Tick:
__array_priority__ = 1000
def __truediv__(self, other):
- result = self.delta.__truediv__(other)
+ if not isinstance(self, _Tick):
+ # cython semantics mean the args are sometimes swapped
+ result = other.delta.__rtruediv__(self)
+ else:
+ result = self.delta.__truediv__(other)
return _wrap_timedelta_result(result)
- def __rtruediv__(self, other):
- result = self.delta.__rtruediv__(other)
- return _wrap_timedelta_result(result)
+ def __reduce__(self):
+ return (type(self), (self.n,))
+
+ def __setstate__(self, state):
+ object.__setattr__(self, "n", state["n"])
class BusinessMixin:
diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index 3f4acca8bce18..cd2ded874c08c 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -9,6 +9,8 @@
from pandas import Index
+from pandas.tseries.offsets import Tick
+
if TYPE_CHECKING:
from pandas import Series, DataFrame
@@ -38,6 +40,11 @@ def load_reduce(self):
return
except TypeError:
pass
+ elif args and issubclass(args[0], Tick):
+ # TypeError: object.__new__(Day) is not safe, use Day.__new__()
+ cls = args[0]
+ stack[-1] = cls.__new__(*args)
+ return
raise
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index 6faebf56a11ab..3b35b54a6dc16 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -173,7 +173,8 @@ def read_pickle(
# 3) try pickle_compat with latin-1 encoding upon a UnicodeDecodeError
try:
- excs_to_catch = (AttributeError, ImportError, ModuleNotFoundError)
+ excs_to_catch = (AttributeError, ImportError, ModuleNotFoundError, TypeError)
+ # TypeError for Cython complaints about object.__new__ vs Tick.__new__
try:
with warnings.catch_warnings(record=True):
# We want to silence any warnings about, e.g. moved modules.
| The actual "PERF" part is that in the follow-up we can cimport `is_tick_object` which will be appreciably faster than the `getattr(other, "_typ", None) == "dateoffset" and hasattr(other, "delta")` checks we now do | https://api.github.com/repos/pandas-dev/pandas/pulls/33979 | 2020-05-04T21:11:26Z | 2020-05-05T16:45:40Z | 2020-05-05T16:45:40Z | 2020-05-05T16:57:58Z |
REF: simplify Timedelta arithmetic methods | diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 7fc22ebf11987..032d3186217e3 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -18,7 +18,8 @@ PyDateTime_IMPORT
cimport pandas._libs.tslibs.util as util
from pandas._libs.tslibs.util cimport (
is_timedelta64_object, is_datetime64_object, is_integer_object,
- is_float_object)
+ is_float_object, is_array
+)
from pandas._libs.tslibs.c_timestamp cimport _Timestamp
@@ -606,7 +607,7 @@ def _binary_op_method_timedeltalike(op, name):
# We are implicitly requiring the canonical behavior to be
# defined by Timestamp methods.
- elif hasattr(other, 'dtype'):
+ elif is_array(other):
# nd-array like
if other.dtype.kind in ['m', 'M']:
return op(self.to_timedelta64(), other)
@@ -1347,113 +1348,64 @@ class Timedelta(_Timedelta):
__rsub__ = _binary_op_method_timedeltalike(lambda x, y: y - x, '__rsub__')
def __mul__(self, other):
- if hasattr(other, '_typ'):
- # Series, DataFrame, ...
- if other._typ == 'dateoffset' and hasattr(other, 'delta'):
- # Tick offset; this op will raise TypeError
- return other.delta * self
- return NotImplemented
+ if is_integer_object(other) or is_float_object(other):
+ return Timedelta(other * self.value, unit='ns')
- elif util.is_nan(other):
- # i.e. np.nan, but also catch np.float64("NaN") which would
- # otherwise get caught by the hasattr(other, "dtype") branch
- # incorrectly return a np.timedelta64 object.
- return NaT
-
- elif hasattr(other, 'dtype'):
+ elif is_array(other):
# ndarray-like
return other * self.to_timedelta64()
- elif other is NaT:
- raise TypeError('Cannot multiply Timedelta with NaT')
-
- elif not (is_integer_object(other) or is_float_object(other)):
- # only integers and floats allowed
- return NotImplemented
-
- return Timedelta(other * self.value, unit='ns')
+ return NotImplemented
__rmul__ = __mul__
def __truediv__(self, other):
- if hasattr(other, '_typ'):
- # Series, DataFrame, ...
- if other._typ == 'dateoffset' and hasattr(other, 'delta'):
- # Tick offset
- return self / other.delta
- return NotImplemented
-
- elif is_timedelta64_object(other):
- # convert to Timedelta below
- pass
-
- elif util.is_nan(other):
- # i.e. np.nan, but also catch np.float64("NaN") which would
- # otherwise get caught by the hasattr(other, "dtype") branch
- # incorrectly return a np.timedelta64 object.
- return NaT
-
- elif hasattr(other, 'dtype'):
- return self.to_timedelta64() / other
+ if _should_cast_to_timedelta(other):
+ # We interpret NaT as timedelta64("NaT")
+ other = Timedelta(other)
+ if other is NaT:
+ return np.nan
+ return self.value / float(other.value)
elif is_integer_object(other) or is_float_object(other):
# integers or floats
return Timedelta(self.value / other, unit='ns')
- elif not _validate_ops_compat(other):
- return NotImplemented
+ elif is_array(other):
+ return self.to_timedelta64() / other
- other = Timedelta(other)
- if other is NaT:
- return np.nan
- return self.value / float(other.value)
+ return NotImplemented
def __rtruediv__(self, other):
- if hasattr(other, '_typ'):
- # Series, DataFrame, ...
- if other._typ == 'dateoffset' and hasattr(other, 'delta'):
- # Tick offset
- return other.delta / self
- return NotImplemented
-
- elif is_timedelta64_object(other):
- # convert to Timedelta below
- pass
-
- elif util.is_nan(other):
- # i.e. np.nan or np.float64("NaN")
- raise TypeError("Cannot divide float by Timedelta")
+ if _should_cast_to_timedelta(other):
+ # We interpret NaT as timedelta64("NaT")
+ other = Timedelta(other)
+ if other is NaT:
+ return np.nan
+ return float(other.value) / self.value
- elif hasattr(other, 'dtype'):
+ elif is_array(other):
if other.dtype.kind == "O":
# GH#31869
return np.array([x / self for x in other])
return other / self.to_timedelta64()
- elif not _validate_ops_compat(other):
- return NotImplemented
-
- other = Timedelta(other)
- if other is NaT:
- # In this context we treat NaT as timedelta-like
- return np.nan
- return float(other.value) / self.value
+ return NotImplemented
def __floordiv__(self, other):
# numpy does not implement floordiv for timedelta64 dtype, so we cannot
# just defer
- if hasattr(other, '_typ'):
- # Series, DataFrame, ...
- if other._typ == 'dateoffset' and hasattr(other, 'delta'):
- # Tick offset
- return self // other.delta
- return NotImplemented
+ if _should_cast_to_timedelta(other):
+ # We interpret NaT as timedelta64("NaT")
+ other = Timedelta(other)
+ if other is NaT:
+ return np.nan
+ return self.value // other.value
- elif is_timedelta64_object(other):
- # convert to Timedelta below
- pass
+ elif is_integer_object(other) or is_float_object(other):
+ return Timedelta(self.value // other, unit='ns')
- elif hasattr(other, 'dtype'):
+ elif is_array(other):
if other.dtype.kind == 'm':
# also timedelta-like
return _broadcast_floordiv_td64(self.value, other, _floordiv)
@@ -1465,32 +1417,19 @@ class Timedelta(_Timedelta):
raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__')
- elif is_integer_object(other) or is_float_object(other):
- return Timedelta(self.value // other, unit='ns')
-
- elif not _validate_ops_compat(other):
- return NotImplemented
-
- other = Timedelta(other)
- if other is NaT:
- return np.nan
- return self.value // other.value
+ return NotImplemented
def __rfloordiv__(self, other):
# numpy does not implement floordiv for timedelta64 dtype, so we cannot
# just defer
- if hasattr(other, '_typ'):
- # Series, DataFrame, ...
- if other._typ == 'dateoffset' and hasattr(other, 'delta'):
- # Tick offset
- return other.delta // self
- return NotImplemented
-
- elif is_timedelta64_object(other):
- # convert to Timedelta below
- pass
+ if _should_cast_to_timedelta(other):
+ # We interpret NaT as timedelta64("NaT")
+ other = Timedelta(other)
+ if other is NaT:
+ return np.nan
+ return other.value // self.value
- elif hasattr(other, 'dtype'):
+ elif is_array(other):
if other.dtype.kind == 'm':
# also timedelta-like
return _broadcast_floordiv_td64(self.value, other, _rfloordiv)
@@ -1498,17 +1437,7 @@ class Timedelta(_Timedelta):
# Includes integer array // Timedelta, disallowed in GH#19761
raise TypeError(f'Invalid dtype {other.dtype} for __floordiv__')
- elif is_float_object(other) and util.is_nan(other):
- # i.e. np.nan
- return NotImplemented
-
- elif not _validate_ops_compat(other):
- return NotImplemented
-
- other = Timedelta(other)
- if other is NaT:
- return np.nan
- return other.value // self.value
+ return NotImplemented
def __mod__(self, other):
# Naive implementation, room for optimization
@@ -1529,6 +1458,21 @@ class Timedelta(_Timedelta):
return div, other - div * self
+cdef bint is_any_td_scalar(object obj):
+ return (
+ PyDelta_Check(obj) or is_timedelta64_object(obj) or isinstance(obj, Tick)
+ )
+
+
+cdef bint _should_cast_to_timedelta(object obj):
+ """
+ Should we treat this object as a Timedelta for the purpose of a binary op
+ """
+ return (
+ is_any_td_scalar(obj) or obj is None or obj is NaT or isinstance(obj, str)
+ )
+
+
cdef _floordiv(int64_t value, right):
return value // right
diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index edda0391f87c9..5a92ee37342d5 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -389,7 +389,8 @@ def test_nat_arithmetic_scalar(op_name, value, val_type):
and "times" in op_name
and isinstance(value, Timedelta)
):
- msg = "Cannot multiply"
+ typs = "(Timedelta|NaTType)"
+ msg = rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'"
elif val_type == "str":
# un-specific check here because the message comes from str
# and varies by method
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index 17d6edfd17de8..2d86ce275de7c 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -325,7 +325,13 @@ class TestTimedeltaMultiplicationDivision:
def test_td_mul_nat(self, op, td_nat):
# GH#19819
td = Timedelta(10, unit="d")
- msg = "cannot use operands with types|Cannot multiply Timedelta with NaT"
+ typs = "|".join(["numpy.timedelta64", "NaTType", "Timedelta"])
+ msg = "|".join(
+ [
+ rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'",
+ r"ufunc '?multiply'? cannot use operands with types",
+ ]
+ )
with pytest.raises(TypeError, match=msg):
op(td, td_nat)
@@ -457,11 +463,11 @@ def test_td_rdiv_na_scalar(self):
result = np.timedelta64("NaT") / td
assert np.isnan(result)
- msg = "cannot use operands with types dtype"
+ msg = r"unsupported operand type\(s\) for /: 'numpy.datetime64' and 'Timedelta'"
with pytest.raises(TypeError, match=msg):
np.datetime64("NaT") / td
- msg = "Cannot divide float by Timedelta"
+ msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"
with pytest.raises(TypeError, match=msg):
np.nan / td
@@ -479,7 +485,7 @@ def test_td_rdiv_ndarray(self):
tm.assert_numpy_array_equal(result, expected)
arr = np.array([np.nan], dtype=object)
- msg = "Cannot divide float by Timedelta"
+ msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"
with pytest.raises(TypeError, match=msg):
arr / td
@@ -522,6 +528,7 @@ def test_td_floordiv_invalid_scalar(self):
[
r"Invalid dtype datetime64\[D\] for __floordiv__",
"'dtype' is an invalid keyword argument for this function",
+ r"ufunc '?floor_divide'? cannot use operands with types",
]
)
with pytest.raises(TypeError, match=msg):
@@ -595,9 +602,14 @@ def test_td_rfloordiv_invalid_scalar(self):
td = Timedelta(hours=3, minutes=3)
dt64 = np.datetime64("2016-01-01", "us")
- msg = r"Invalid dtype datetime64\[us\] for __floordiv__"
+
+ assert td.__rfloordiv__(dt64) is NotImplemented
+
+ msg = (
+ r"unsupported operand type\(s\) for //: 'numpy.datetime64' and 'Timedelta'"
+ )
with pytest.raises(TypeError, match=msg):
- td.__rfloordiv__(dt64)
+ dt64 // td
def test_td_rfloordiv_numeric_scalar(self):
# GH#18846
@@ -606,15 +618,18 @@ def test_td_rfloordiv_numeric_scalar(self):
assert td.__rfloordiv__(np.nan) is NotImplemented
assert td.__rfloordiv__(3.5) is NotImplemented
assert td.__rfloordiv__(2) is NotImplemented
+ assert td.__rfloordiv__(np.float64(2.0)) is NotImplemented
+ assert td.__rfloordiv__(np.uint8(9)) is NotImplemented
+ assert td.__rfloordiv__(np.int32(2.0)) is NotImplemented
- msg = "Invalid dtype"
+ msg = r"unsupported operand type\(s\) for //: '.*' and 'Timedelta"
with pytest.raises(TypeError, match=msg):
- td.__rfloordiv__(np.float64(2.0))
+ np.float64(2.0) // td
with pytest.raises(TypeError, match=msg):
- td.__rfloordiv__(np.uint8(9))
+ np.uint8(9) // td
with pytest.raises(TypeError, match=msg):
# deprecated GH#19761, enforced GH#29797
- td.__rfloordiv__(np.int32(2.0))
+ np.int32(2.0) // td
def test_td_rfloordiv_timedeltalike_array(self):
# GH#18846
| In particular this avoids the "_typ" checks which go through python-space | https://api.github.com/repos/pandas-dev/pandas/pulls/33978 | 2020-05-04T20:06:45Z | 2020-05-06T06:48:59Z | 2020-05-06T06:48:59Z | 2020-05-06T14:11:03Z |
DOC: whatsnew for 33717 | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 6eedf9dee5266..9f9236d173dbd 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -561,6 +561,7 @@ Datetimelike
- 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`)
- Bug in :meth:`DatetimeIndex.intersection` and :meth:`TimedeltaIndex.intersection` with results not having the correct ``name`` attribute (:issue:`33904`)
+- Bug in :meth:`DatetimeArray.__setitem__`, :meth:`TimedeltaArray.__setitem__`, :meth:`PeriodArray.__setitem__` incorrectly allowing values with ``int64`` dtype to be silently cast (:issue:`33717`)
Timedelta
^^^^^^^^^
| xref #33717 | https://api.github.com/repos/pandas-dev/pandas/pulls/33977 | 2020-05-04T20:02:42Z | 2020-05-04T22:10:42Z | 2020-05-04T22:10:42Z | 2020-05-04T22:30:50Z |
Backport PR #31146 on branch 1.0.x (Remove possibly illegal test data) | diff --git a/pandas/tests/io/data/html/computer_sales_page.html b/pandas/tests/io/data/html/computer_sales_page.html
deleted file mode 100644
index ff2b031b58d64..0000000000000
--- a/pandas/tests/io/data/html/computer_sales_page.html
+++ /dev/null
@@ -1,619 +0,0 @@
-<table width="100%" border="0" cellspacing="0" cellpadding="0">
-<tbody><tr><!-- TABLE COLUMN WIDTHS SET -->
-<td width="" style="font-family:times;"></td>
-<td width="12pt" style="font-family:times;"></td>
-<td width="7pt" align="RIGHT" style="font-family:times;"></td>
-<td width="45pt" style="font-family:times;"></td>
-<td width="12pt" style="font-family:times;"></td>
-<td width="7pt" align="RIGHT" style="font-family:times;"></td>
-<td width="45pt" style="font-family:times;"></td>
-<td width="12pt" style="font-family:times;"></td>
-<td width="7pt" align="RIGHT" style="font-family:times;"></td>
-<td width="45pt" style="font-family:times;"></td>
-<td width="12pt" style="font-family:times;"></td>
-<td width="7pt" align="RIGHT" style="font-family:times;"></td>
-<td width="45pt" style="font-family:times;"></td>
-<td width="12pt" style="font-family:times;"></td>
-<!-- TABLE COLUMN WIDTHS END --></tr>
-
-<tr valign="BOTTOM">
-<th align="LEFT" style="font-family:times;"><font size="2"> </font><br></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="5" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>Three months ended<br>
-April 30 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="5" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>Six months ended<br>
-April 30 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-</tr>
-<tr valign="BOTTOM">
-<th align="LEFT" style="font-family:times;"><font size="1"> </font><br></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="2" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>2013 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="2" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>2012 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="2" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>2013 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="2" align="CENTER" style="font-family:times;border-bottom:solid #000000 1.0pt;"><font size="1"><b>2012 </b></font></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-</tr>
-<tr valign="BOTTOM">
-<th align="LEFT" style="font-family:times;"><font size="1"> </font><br></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-<th colspan="11" align="CENTER" style="font-family:times;"><font size="1"><b>In millions</b></font><br></th>
-<th style="font-family:times;"><font size="1"> </font></th>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Net revenue:</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Notebooks</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,718</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,900</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,846</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">9,842</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Desktops</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,103</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,827</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,424</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,033</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Workstations</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">521</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">537</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,056</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,072</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Other</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">242</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">206</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">462</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">415</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Personal Systems</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,584</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">9,470</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">15,788</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">18,362</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Supplies</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,122</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,060</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">8,015</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">8,139</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Commercial Hardware</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,398</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,479</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,752</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,968</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Consumer Hardware</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">561</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">593</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,240</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,283</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Printing</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,081</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,132</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">12,007</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">12,390</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Printing and Personal Systems Group</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">13,665</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">15,602</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">27,795</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">30,752</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Industry Standard Servers</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,806</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,186</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">5,800</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,258</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Technology Services</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,272</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,335</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,515</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,599</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Storage</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">857</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">990</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,690</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,945</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Networking</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">618</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">614</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,226</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,200</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Business Critical Systems</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">266</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">421</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">572</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">826</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Enterprise Group</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,819</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,546</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">13,803</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">14,828</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Infrastructure Technology Outsourcing</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,721</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">3,954</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,457</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7,934</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:20pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Application and Business Services</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,278</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">2,535</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,461</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">4,926</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Enterprise Services</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">5,999</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">6,489</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">11,918</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">12,860</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Software</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">941</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">970</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,867</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,916</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">HP Financial Services</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">881</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">968</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,838</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">1,918</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Corporate Investments</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">10</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">7</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">14</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">37</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Total segments</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">28,315</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">31,582</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">57,235</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">62,311</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="#CCEEFF" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:10pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Eliminations of intersegment net revenue and other</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">(733</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2">)</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">(889</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2">)</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">(1,294</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2">)</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">(1,582</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2">)</font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:solid #000000 1.0pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-<tr bgcolor="White" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"><p style="font-family:times;margin-left:30pt;text-indent:-10pt;"><font size="2"> </font><font size="2">Total HP consolidated net revenue</font></p></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">27,582</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">30,693</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">55,941</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">$</font></td>
-<td align="RIGHT" valign="BOTTOM" style="font-family:times;"><font size="2">60,729</font></td>
-<td valign="BOTTOM" style="font-family:times;"><font size="2"> </font></td>
-</tr>
-<tr style="font-size:1.5pt;" valign="TOP">
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:double #000000 2.25pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:double #000000 2.25pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:double #000000 2.25pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-<td colspan="2" align="RIGHT" valign="BOTTOM" style="font-family:times;border-bottom:double #000000 2.25pt;"> </td>
-<td valign="BOTTOM" style="font-family:times;"> </td>
-</tr>
-</tbody></table>
diff --git a/pandas/tests/io/data/html/macau.html b/pandas/tests/io/data/html/macau.html
deleted file mode 100644
index edc4ea96f0f20..0000000000000
--- a/pandas/tests/io/data/html/macau.html
+++ /dev/null
@@ -1,3691 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-<!-- saved from url=(0037)http://www.camacau.com/statistic_list -->
-<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
-
-<link rel="stylesheet" type="text/css" href="./macau_files/style.css" media="screen">
-<script type="text/javascript" src="./macau_files/jquery.js"></script>
-
-
-
-
-
-<script type="text/javascript">
-
-function slideSwitch() {
-
- var $active = $('#banner1 a.active');
-
- var totalTmp=document.getElementById("bannerTotal").innerHTML;
-
- var randomTmp=Math.floor(Math.random()*totalTmp+1);
-
- var $next = $('#image'+randomTmp).length?$('#image'+randomTmp):$('#banner1 a:first');
-
- if($next.attr("id")==$active.attr("id")){
-
- $next = $active.next().length ? $active.next():$('#banner1 a:first');
- }
-
- $active.removeClass("active");
-
- $next.addClass("active").show();
-
- $active.hide();
-
-}
-
-jQuery(function() {
-
- var totalTmp=document.getElementById("bannerTotal").innerHTML;
- if(totalTmp>1){
- setInterval( "slideSwitch()", 5000 );
- }
-
-});
-
-</script>
-<script type="text/javascript">
-function close_notice(){
-jQuery("#tbNotice").hide();
-}
-</script>
-
-<title>Traffic Statistics - Passengers</title>
-
-<!-- GOOGLE STATISTICS
-<script type="text/javascript">
-
- var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-24989877-2']);
- _gaq.push(['_trackPageview']);
-
- (function() {
- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
- })();
-
-</script>
--->
-<style type="text/css"></style><style type="text/css"></style><script id="fireplug-jssdk" src="./macau_files/all.js"></script><style type="text/css">.fireplug-credit-widget-overlay{z-index:9999999999999999999;background-color:rgba(91,91,91,0.6)}.fireplug-credit-widget-overlay div,.fireplug-credit-widget-overlay span,.fireplug-credit-widget-overlay applet,.fireplug-credit-widget-overlay object,.fireplug-credit-widget-overlay iframe,.fireplug-credit-widget-overlay h1,.fireplug-credit-widget-overlay h2,.fireplug-credit-widget-overlay h3,.fireplug-credit-widget-overlay h4,.fireplug-credit-widget-overlay h5,.fireplug-credit-widget-overlay h6,.fireplug-credit-widget-overlay p,.fireplug-credit-widget-overlay blockquote,.fireplug-credit-widget-overlay pre,.fireplug-credit-widget-overlay a,.fireplug-credit-widget-overlay abbr,.fireplug-credit-widget-overlay acronym,.fireplug-credit-widget-overlay address,.fireplug-credit-widget-overlay big,.fireplug-credit-widget-overlay cite,.fireplug-credit-widget-overlay code,.fireplug-credit-widget-overlay del,.fireplug-credit-widget-overlay dfn,.fireplug-credit-widget-overlay em,.fireplug-credit-widget-overlay img,.fireplug-credit-widget-overlay ins,.fireplug-credit-widget-overlay kbd,.fireplug-credit-widget-overlay q,.fireplug-credit-widget-overlay s,.fireplug-credit-widget-overlay samp,.fireplug-credit-widget-overlay small,.fireplug-credit-widget-overlay strike,.fireplug-credit-widget-overlay strong,.fireplug-credit-widget-overlay sub,.fireplug-credit-widget-overlay sup,.fireplug-credit-widget-overlay tt,.fireplug-credit-widget-overlay var,.fireplug-credit-widget-overlay b,.fireplug-credit-widget-overlay u,.fireplug-credit-widget-overlay i,.fireplug-credit-widget-overlay center,.fireplug-credit-widget-overlay dl,.fireplug-credit-widget-overlay dt,.fireplug-credit-widget-overlay dd,.fireplug-credit-widget-overlay ol,.fireplug-credit-widget-overlay ul,.fireplug-credit-widget-overlay li,.fireplug-credit-widget-overlay fieldset,.fireplug-credit-widget-overlay form,.fireplug-credit-widget-overlay label,.fireplug-credit-widget-overlay legend,.fireplug-credit-widget-overlay table,.fireplug-credit-widget-overlay caption,.fireplug-credit-widget-overlay tbody,.fireplug-credit-widget-overlay tfoot,.fireplug-credit-widget-overlay thead,.fireplug-credit-widget-overlay tr,.fireplug-credit-widget-overlay th,.fireplug-credit-widget-overlay td,.fireplug-credit-widget-overlay article,.fireplug-credit-widget-overlay aside,.fireplug-credit-widget-overlay canvas,.fireplug-credit-widget-overlay details,.fireplug-credit-widget-overlay embed,.fireplug-credit-widget-overlay figure,.fireplug-credit-widget-overlay figcaption,.fireplug-credit-widget-overlay footer,.fireplug-credit-widget-overlay header,.fireplug-credit-widget-overlay hgroup,.fireplug-credit-widget-overlay menu,.fireplug-credit-widget-overlay nav,.fireplug-credit-widget-overlay output,.fireplug-credit-widget-overlay ruby,.fireplug-credit-widget-overlay section,.fireplug-credit-widget-overlay summary,.fireplug-credit-widget-overlay time,.fireplug-credit-widget-overlay mark,.fireplug-credit-widget-overlay audio,.fireplug-credit-widget-overlay video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}.fireplug-credit-widget-overlay table{border-collapse:collapse;border-spacing:0}.fireplug-credit-widget-overlay caption,.fireplug-credit-widget-overlay th,.fireplug-credit-widget-overlay td{text-align:left;font-weight:normal;vertical-align:middle}.fireplug-credit-widget-overlay q,.fireplug-credit-widget-overlay blockquote{quotes:none}.fireplug-credit-widget-overlay q:before,.fireplug-credit-widget-overlay q:after,.fireplug-credit-widget-overlay blockquote:before,.fireplug-credit-widget-overlay blockquote:after{content:"";content:none}.fireplug-credit-widget-overlay a img{border:none}.fireplug-credit-widget-overlay .fireplug-credit-widget-overlay-item{z-index:9999999999999999999;-webkit-box-shadow:#333 0px 0px 10px;-moz-box-shadow:#333 0px 0px 10px;box-shadow:#333 0px 0px 10px}.fireplug-credit-widget-overlay-body{height:100% !important;overflow:hidden !important}.fp-getcredit iframe{border:none;overflow:hidden;height:20px;width:145px}
-</style></head>
-<body>
-<div id="full">
-<div id="container">
-
-
-<div id="top">
- <div id="lang">
-
- <a href="http://www.camacau.com/changeLang?lang=zh_TW&url=/statistic_list">繁體中文</a> |
- <a href="http://www.camacau.com/changeLang?lang=zh_CN&url=/statistic_list">簡體中文</a>
- <!--<a href="changeLang?lang=pt_PT&url=/statistic_list" >Portuguese</a>
- -->
- </div>
-</div>
-
-<div id="header">
- <div id="sitelogo"><a href="http://www.camacau.com/index" style="color : #FFF;"><img src="./macau_files/cam h04.jpg"></a></div>
- <div id="navcontainer">
- <div id="menu">
- <div id="search">
- <form id="searchForm" name="searchForm" action="http://www.camacau.com/search" method="POST">
- <input id="keyword" name="keyword" type="text">
- <a href="javascript:document.searchForm.submit();">Search</a> |
- <a href="mailto:mkd@macau-airport.com">Contact Us</a> |
- <a href="http://www.camacau.com/sitemap">SiteMap</a> |
-
- <a href="http://www.camacau.com/rssBuilder.action"><img src="./macau_files/rssIcon.png" alt="RSS">RSS</a>
- </form></div>
- </div>
-</div>
-</div>
-<div id="menu2">
- <div>
-
-
- <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Main Page">
- <param name="movie" value="flash/button_index_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_index_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Our Business">
- <param name="movie" value="flash/button_our business_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_our%20business_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="About Us">
- <param name="movie" value="flash/button_about us_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_about%20us_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <object id="FlashID3" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="Media Centre">
- <param name="movie" value="flash/button_media centre_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_media%20centre_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="wmode" value="opaque">
- <param name="scale" value="exactfit">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID5" title="Related Links">
- <param name="movie" value="flash/button_related links_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_related%20links_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <object id="FlashID2" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="Interactive">
- <param name="movie" value="flash/button_interactive_EN.swf">
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 -->
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 -->
- <!--[if !IE]>-->
- <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_interactive_EN.swf" width="92" height="20">
- <!--<![endif]-->
- <param name="quality" value="high">
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque">
- <param name="swfversion" value="6.0.65.0">
- <param name="expressinstall" value="flash/expressInstall.swf">
- <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 -->
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p>
- </div>
- <!--[if !IE]>-->
- </object>
- <!--<![endif]-->
- </object>
-
- <!--<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Group of Public">
- <param name="movie" value="flash/button_pressRelease_EN.swf" />
- <param name="quality" value="high" />
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque" />
- <param name="swfversion" value="6.0.65.0" />
- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。
- <param name="expressinstall" value="flash/expressInstall.swf" />
- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。
- [if !IE]>
- <object type="application/x-shockwave-flash" data="flash/button_pressRelease_EN.swf" width="92" height="20">
- <![endif]
- <param name="quality" value="high" />
- <param name="scale" value="exactfit">
- <param name="wmode" value="opaque" />
- <param name="swfversion" value="6.0.65.0" />
- <param name="expressinstall" value="flash/expressInstall.swf" />
- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。
- <div>
- <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4>
- <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33" /></a></p>
- </div>
- [if !IE]>
- </object>
- <![endif]
- </object>
-
- --></div>
- </div>
-
-
-
-
-
-
-
-<style>
-#slider ul li
-{
-height: 90px;
-list-style:none;
-width:95%;
-font-size:11pt;
-text-indent:2em;
-text-align:justify;
-text-justify:inter-ideograph;
-color:#663300;
-}
-
-
-#slider
-{
-margin: auto;
-overflow: hidden;
-/* Non Core */
-background: #f6f7f8;
-box-shadow: 4px 4px 15px #aaa;
--o-box-shadow: 4px 4px 15px #aaa;
--icab-box-shadow: 4px 4px 15px #aaa;
--khtml-box-shadow: 4px 4px 15px #aaa;
--moz-box-shadow: 4px 4px 15px #aaa;
--webkit-box-shadow: 4px 4px 15px #aaa;
-border: 4px solid #bcc5cb;
-
-border-width: 1px 2px 2px 1px;
-
--o-border-radius: 10px;
--icab-border-radius: 10px;
--khtml-border-radius: 10px;
--moz-border-radius: 10px;
--webkit-border-radius: 10px;
-border-radius: 10px;
-
-}
-
-#close_tbNotice img
-{
-width:20px;
-height:20px;
-align:right;
-cursor:pointer;
-}
-</style>
-
-<div id="banner">
- <!--<div id="leftGradient"></div>-->
-
- <table id="tbNotice" style="display:none;width:800px;z-index:999;position:absolute;left:20%;" align="center">
- <tbody><tr height="40px"><td></td></tr>
- <tr><td>
-
- <div id="slider">
- <div id="close_tbNotice"><img src="./macau_files/delete.png" onclick="close_notice()"></div>
- <ul>
- <li>
-
-
-
-
- </li>
- </ul>
-
- </div>
- <div id="show_notice" style="display:none;">
-
- </div>
-
- </td>
-
- </tr>
- <tr><td align="right"></td></tr>
- </tbody></table>
-
-
- <div class="gradient">
-
- </div>
- <div class="banner1" id="banner1">
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image1" class="">
- <img src="./macau_files/41.jpeg" alt="Slideshow Image 1">
- </a>
-
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image2" class="">
- <img src="./macau_files/45.jpeg" alt="Slideshow Image 2">
- </a>
-
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image3" class="">
- <img src="./macau_files/46.jpeg" alt="Slideshow Image 3">
- </a>
-
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: inline;" id="image4" class="active">
- <img src="./macau_files/47.jpeg" alt="Slideshow Image 4">
- </a>
-
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image5" class="">
- <img src="./macau_files/48.jpeg" alt="Slideshow Image 5">
- </a>
-
-
-
-
-
- <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image6" class="">
- <img src="./macau_files/49.jpeg" alt="Slideshow Image 6">
- </a>
-
-
-
-
-
- <a href="http://www.4cpscac.com/" target="_blank" style="display: none;" id="image7" class="">
- <img src="./macau_files/50.jpg" alt="Slideshow Image 7">
- </a>
-
-
-
-
- </div>
- <div id="bannerTotal" style="display:none;">7</div>
-</div>
-
-<div id="content">
- <div id="leftnav">
-
- <div id="navmenu">
-
-
-
-
-
-<link href="./macau_files/ddaccordion.css" rel="stylesheet" type="text/css">
-<script type="text/javascript" src="./macau_files/ddaccordion.js"></script>
-
-
-
-<script type="text/javascript">
- ddaccordion.init({
- headerclass: "leftmenu_silverheader", //Shared CSS class name of headers group
- contentclass: "leftmenu_submenu", //Shared CSS class name of contents group
- revealtype: "clickgo", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
- mouseoverdelay: 100, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
- collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
- defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content
- onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
- animatedefault: true, //Should contents open by default be animated into view?
- persiststate: true, //persist state of opened contents within browser session?
- toggleclass: ["", "selected"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
- togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively ["position", "html1", "html2"] (see docs)
- animatespeed: "normal", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
- oninit:function(headers, expandedindices){ //custom code to run when headers have initialized
- //do nothing
- },
- onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
- //do nothing
-
- }
-});
-</script><style type="text/css">
-.leftmenu_submenu{display: none}
-a.hiddenajaxlink{display: none}
-</style>
-
-
- <table>
- <tbody><tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/geographic_information">MIA Geographical Information</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/airport_services">Scope of Service</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/services_agreement">Air Services Agreement</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/airport_charges" class="leftmenu_silverheader selected" headerindex="0h"><span>Airport Charges</span></a></td></tr>
- <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;">
- <table class="leftmenu_submenu" contentindex="0c" style="display: block;">
- <tbody><tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges1">Passenger Service Fees</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges2">Aircraft Parking fees</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges3">Airport Security Fee</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges4">Utilization fees</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges5">Refuelling Charge</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/calculation">Calculation of Landing fee Rate</a></td></tr></tbody></table></td></tr>
- </tbody></table>
- </td>
- </tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/application_facilities">Application of Credit Facilities</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="javascript:void(0)" class="leftmenu_silverheader " headerindex="1h"><span>Passenger Flight Incentive Program</span></a></td></tr>
- <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;">
- <table class="leftmenu_submenu" contentindex="1c" style="display: none;">
- <tbody><tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1">Incentive policy for new routes and additional flights</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1_1">Passenger flights</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1_2">Charter flights</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/docs/MIA_Route_Development_IncentiveApp_Form.pdf" target="_blank">Route Development Incentive Application Form</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/online_application">Online Application</a></td></tr></tbody></table></td></tr>
- </tbody></table>
- </td>
- </tr>
-
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/slot_application">Slot Application</a></td></tr>
-
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/freighter_forwards">Macau Freight Forwarders</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/ctplatform">Cargo Tracking Platform</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/for_rent">For Rent</a></td></tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/capacity">Airport Capacity</a></td></tr>
-
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td style="color: #606060;text-decoration: none;"><a href="javascript:void(0)" class="leftmenu_silverheader " headerindex="2h">Airport Characteristics & Traffic Statistics</a></td></tr>
- <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;">
- <table class="leftmenu_submenu" contentindex="2c" style="display: none;">
- <!--<tr><td> </td><td><table class="submenu"><tr><td><img width="20" height="15" src="images/sub_icon.gif"/></td><td><a href="airport_characteristics">Airport Characteristics</a></td></tr></table></td></tr>
- -->
- <tbody><tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="./macau_files/macau.html">Traffic Statistics - Passengers</a></td></tr></tbody></table></td></tr>
- <tr><td> </td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/statistics_cargo">Traffic Statistics - Cargo</a></td></tr></tbody></table></td></tr>
- </tbody></table>
- </td>
- </tr>
- <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/operational_routes">Operational Routes</a></td></tr>
-
- <!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="route_development">Member Registration</a></td></tr>
-
- --><!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="cargo_arrival">Cargo Flight Information</a></td></tr>-->
-
- <!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="/mvnforum/mvnforum/index">Forum</a></td></tr>-->
-
- </tbody></table>
-
-
- </div>
- </div>
-
-<div id="under">
- <div id="contextTitle">
- <h2 class="con">Traffic Statistics - Passengers</h2>
-
- </div>
- <div class="contextTitleAfter"></div>
- <div>
-
-
- <div id="context">
- <!--/*begin context*/-->
- <div class="Container">
- <div id="Scroller-1">
- <div class="Scroller-Container">
- <div id="statisticspassengers" style="width:550px;">
-
-
- <span id="title">Traffic Statistics</span>
-
-
-
-
-
- <br><br><br>
- <span id="title">Passengers Figure(2008-2013) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2013</th>
-
- <th align="center">2012</th>
-
- <th align="center">2011</th>
-
- <th align="center">2010</th>
-
- <th align="center">2009</th>
-
- <th align="center">2008</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 374,917
- </td>
-
- <td align="center">
-
- 362,379
- </td>
-
- <td align="center">
-
- 301,503
- </td>
-
- <td align="center">
-
- 358,902
- </td>
-
- <td align="center">
-
- 342,323
- </td>
-
- <td align="center">
-
- 420,574
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 393,152
- </td>
-
- <td align="center">
-
- 312,405
- </td>
-
- <td align="center">
-
- 301,259
- </td>
-
- <td align="center">
-
- 351,654
- </td>
-
- <td align="center">
-
- 297,755
- </td>
-
- <td align="center">
-
- 442,809
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 408,755
- </td>
-
- <td align="center">
-
- 334,000
- </td>
-
- <td align="center">
-
- 318,908
- </td>
-
- <td align="center">
-
- 360,365
- </td>
-
- <td align="center">
-
- 387,879
- </td>
-
- <td align="center">
-
- 468,540
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 408,860
- </td>
-
- <td align="center">
-
- 358,198
- </td>
-
- <td align="center">
-
- 339,060
- </td>
-
- <td align="center">
-
- 352,976
- </td>
-
- <td align="center">
-
- 400,553
- </td>
-
- <td align="center">
-
- 492,930
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 374,397
- </td>
-
- <td align="center">
-
- 329,218
- </td>
-
- <td align="center">
-
- 321,060
- </td>
-
- <td align="center">
-
- 330,407
- </td>
-
- <td align="center">
-
- 335,967
- </td>
-
- <td align="center">
-
- 465,045
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 401,995
- </td>
-
- <td align="center">
-
- 356,679
- </td>
-
- <td align="center">
-
- 343,006
- </td>
-
- <td align="center">
-
- 326,724
- </td>
-
- <td align="center">
-
- 296,748
- </td>
-
- <td align="center">
-
- 426,764
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 423,081
- </td>
-
- <td align="center">
-
- 378,993
- </td>
-
- <td align="center">
-
- 356,580
- </td>
-
- <td align="center">
-
- 351,110
- </td>
-
- <td align="center">
-
- 439,425
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 453,391
- </td>
-
- <td align="center">
-
- 395,883
- </td>
-
- <td align="center">
-
- 364,011
- </td>
-
- <td align="center">
-
- 404,076
- </td>
-
- <td align="center">
-
- 425,814
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 384,887
- </td>
-
- <td align="center">
-
- 325,124
- </td>
-
- <td align="center">
-
- 308,940
- </td>
-
- <td align="center">
-
- 317,226
- </td>
-
- <td align="center">
-
- 379,898
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 383,889
- </td>
-
- <td align="center">
-
- 333,102
- </td>
-
- <td align="center">
-
- 317,040
- </td>
-
- <td align="center">
-
- 355,935
- </td>
-
- <td align="center">
-
- 415,339
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 379,065
- </td>
-
- <td align="center">
-
- 327,803
- </td>
-
- <td align="center">
-
- 303,186
- </td>
-
- <td align="center">
-
- 372,104
- </td>
-
- <td align="center">
-
- 366,411
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 413,873
- </td>
-
- <td align="center">
-
- 359,313
- </td>
-
- <td align="center">
-
- 348,051
- </td>
-
- <td align="center">
-
- 388,573
- </td>
-
- <td align="center">
-
- 354,253
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 2,362,076
- </td>
-
- <td align="center">
-
- 4,491,065
- </td>
-
- <td align="center">
-
- 4,045,014
- </td>
-
- <td align="center">
-
- 4,078,836
- </td>
-
- <td align="center">
-
- 4,250,249
- </td>
-
- <td align="center">
-
- 5,097,802
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Passengers Figure(2002-2007) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2007</th>
-
- <th align="center">2006</th>
-
- <th align="center">2005</th>
-
- <th align="center">2004</th>
-
- <th align="center">2003</th>
-
- <th align="center">2002</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 381,887
- </td>
-
- <td align="center">
-
- 323,282
- </td>
-
- <td align="center">
-
- 289,701
- </td>
-
- <td align="center">
-
- 288,507
- </td>
-
- <td align="center">
-
- 290,140
- </td>
-
- <td align="center">
-
- 268,783
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 426,014
- </td>
-
- <td align="center">
-
- 360,820
- </td>
-
- <td align="center">
-
- 348,723
- </td>
-
- <td align="center">
-
- 207,710
- </td>
-
- <td align="center">
-
- 323,264
- </td>
-
- <td align="center">
-
- 323,654
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 443,805
- </td>
-
- <td align="center">
-
- 389,125
- </td>
-
- <td align="center">
-
- 321,953
- </td>
-
- <td align="center">
-
- 273,910
- </td>
-
- <td align="center">
-
- 295,052
- </td>
-
- <td align="center">
-
- 360,668
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 500,917
- </td>
-
- <td align="center">
-
- 431,550
- </td>
-
- <td align="center">
-
- 367,976
- </td>
-
- <td align="center">
-
- 324,931
- </td>
-
- <td align="center">
-
- 144,082
- </td>
-
- <td align="center">
-
- 380,648
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 468,637
- </td>
-
- <td align="center">
-
- 399,743
- </td>
-
- <td align="center">
-
- 359,298
- </td>
-
- <td align="center">
-
- 250,601
- </td>
-
- <td align="center">
-
- 47,333
- </td>
-
- <td align="center">
-
- 359,547
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 463,676
- </td>
-
- <td align="center">
-
- 393,713
- </td>
-
- <td align="center">
-
- 360,147
- </td>
-
- <td align="center">
-
- 296,000
- </td>
-
- <td align="center">
-
- 94,294
- </td>
-
- <td align="center">
-
- 326,508
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
- 490,404
- </td>
-
- <td align="center">
-
- 465,497
- </td>
-
- <td align="center">
-
- 413,131
- </td>
-
- <td align="center">
-
- 365,454
- </td>
-
- <td align="center">
-
- 272,784
- </td>
-
- <td align="center">
-
- 388,061
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
- 490,830
- </td>
-
- <td align="center">
-
- 478,474
- </td>
-
- <td align="center">
-
- 409,281
- </td>
-
- <td align="center">
-
- 372,802
- </td>
-
- <td align="center">
-
- 333,840
- </td>
-
- <td align="center">
-
- 384,719
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
- 446,594
- </td>
-
- <td align="center">
-
- 412,444
- </td>
-
- <td align="center">
-
- 354,751
- </td>
-
- <td align="center">
-
- 321,456
- </td>
-
- <td align="center">
-
- 295,447
- </td>
-
- <td align="center">
-
- 334,029
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
- 465,757
- </td>
-
- <td align="center">
-
- 461,215
- </td>
-
- <td align="center">
-
- 390,435
- </td>
-
- <td align="center">
-
- 358,362
- </td>
-
- <td align="center">
-
- 291,193
- </td>
-
- <td align="center">
-
- 372,706
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 455,132
- </td>
-
- <td align="center">
-
- 425,116
- </td>
-
- <td align="center">
-
- 323,347
- </td>
-
- <td align="center">
-
- 327,593
- </td>
-
- <td align="center">
-
- 268,282
- </td>
-
- <td align="center">
-
- 350,324
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 465,225
- </td>
-
- <td align="center">
-
- 435,114
- </td>
-
- <td align="center">
-
- 308,999
- </td>
-
- <td align="center">
-
- 326,933
- </td>
-
- <td align="center">
-
- 249,855
- </td>
-
- <td align="center">
-
- 322,056
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 5,498,878
- </td>
-
- <td align="center">
-
- 4,976,093
- </td>
-
- <td align="center">
-
- 4,247,742
- </td>
-
- <td align="center">
-
- 3,714,259
- </td>
-
- <td align="center">
-
- 2,905,566
- </td>
-
- <td align="center">
-
- 4,171,703
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Passengers Figure(1996-2001) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2001</th>
-
- <th align="center">2000</th>
-
- <th align="center">1999</th>
-
- <th align="center">1998</th>
-
- <th align="center">1997</th>
-
- <th align="center">1996</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 265,603
- </td>
-
- <td align="center">
-
- 184,381
- </td>
-
- <td align="center">
-
- 161,264
- </td>
-
- <td align="center">
-
- 161,432
- </td>
-
- <td align="center">
-
- 117,984
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 249,259
- </td>
-
- <td align="center">
-
- 264,066
- </td>
-
- <td align="center">
-
- 209,569
- </td>
-
- <td align="center">
-
- 168,777
- </td>
-
- <td align="center">
-
- 150,772
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 312,319
- </td>
-
- <td align="center">
-
- 226,483
- </td>
-
- <td align="center">
-
- 186,965
- </td>
-
- <td align="center">
-
- 172,060
- </td>
-
- <td align="center">
-
- 149,795
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 351,793
- </td>
-
- <td align="center">
-
- 296,541
- </td>
-
- <td align="center">
-
- 237,449
- </td>
-
- <td align="center">
-
- 180,241
- </td>
-
- <td align="center">
-
- 179,049
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 338,692
- </td>
-
- <td align="center">
-
- 288,949
- </td>
-
- <td align="center">
-
- 230,691
- </td>
-
- <td align="center">
-
- 172,391
- </td>
-
- <td align="center">
-
- 189,925
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 332,630
- </td>
-
- <td align="center">
-
- 271,181
- </td>
-
- <td align="center">
-
- 231,328
- </td>
-
- <td align="center">
-
- 157,519
- </td>
-
- <td align="center">
-
- 175,402
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
- 344,658
- </td>
-
- <td align="center">
-
- 304,276
- </td>
-
- <td align="center">
-
- 243,534
- </td>
-
- <td align="center">
-
- 205,595
- </td>
-
- <td align="center">
-
- 173,103
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
- 360,899
- </td>
-
- <td align="center">
-
- 300,418
- </td>
-
- <td align="center">
-
- 257,616
- </td>
-
- <td align="center">
-
- 241,140
- </td>
-
- <td align="center">
-
- 178,118
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
- 291,817
- </td>
-
- <td align="center">
-
- 280,803
- </td>
-
- <td align="center">
-
- 210,885
- </td>
-
- <td align="center">
-
- 183,954
- </td>
-
- <td align="center">
-
- 163,385
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
- 327,232
- </td>
-
- <td align="center">
-
- 298,873
- </td>
-
- <td align="center">
-
- 231,251
- </td>
-
- <td align="center">
-
- 205,726
- </td>
-
- <td align="center">
-
- 176,879
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 315,538
- </td>
-
- <td align="center">
-
- 265,528
- </td>
-
- <td align="center">
-
- 228,637
- </td>
-
- <td align="center">
-
- 181,677
- </td>
-
- <td align="center">
-
- 146,804
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 314,866
- </td>
-
- <td align="center">
-
- 257,929
- </td>
-
- <td align="center">
-
- 210,922
- </td>
-
- <td align="center">
-
- 183,975
- </td>
-
- <td align="center">
-
- 151,362
- </td>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 3,805,306
- </td>
-
- <td align="center">
-
- 3,239,428
- </td>
-
- <td align="center">
-
- 2,640,111
- </td>
-
- <td align="center">
-
- 2,214,487
- </td>
-
- <td align="center">
-
- 1,952,578
- </td>
-
- <td align="center">
-
- 0
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Passengers Figure(1995-1995) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">1995</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 6,601
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 37,041
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 43,642
- </td>
-
- </tr>
- </tbody>
- </table>
-
-
- <br><br><br>
- <div align="right"><img src="./macau_files/pass_stat.jpg" alt="passenger statistic picture" width="565" height="318"></div>
- <br><br><br>
-
-
- <!--statistics-movement -->
-
- <br><br><br>
- <span id="title">Movement Statistics(2008-2013) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2013</th>
-
- <th align="center">2012</th>
-
- <th align="center">2011</th>
-
- <th align="center">2010</th>
-
- <th align="center">2009</th>
-
- <th align="center">2008</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 3,925
- </td>
-
- <td align="center">
-
- 3,463
- </td>
-
- <td align="center">
-
- 3,289
- </td>
-
- <td align="center">
-
- 3,184
- </td>
-
- <td align="center">
-
- 3,488
- </td>
-
- <td align="center">
-
- 4,568
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 3,632
- </td>
-
- <td align="center">
-
- 2,983
- </td>
-
- <td align="center">
-
- 2,902
- </td>
-
- <td align="center">
-
- 3,053
- </td>
-
- <td align="center">
-
- 3,347
- </td>
-
- <td align="center">
-
- 4,527
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 3,909
- </td>
-
- <td align="center">
-
- 3,166
- </td>
-
- <td align="center">
-
- 3,217
- </td>
-
- <td align="center">
-
- 3,175
- </td>
-
- <td align="center">
-
- 3,636
- </td>
-
- <td align="center">
-
- 4,594
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 3,903
- </td>
-
- <td align="center">
-
- 3,258
- </td>
-
- <td align="center">
-
- 3,146
- </td>
-
- <td align="center">
-
- 3,023
- </td>
-
- <td align="center">
-
- 3,709
- </td>
-
- <td align="center">
-
- 4,574
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 4,075
- </td>
-
- <td align="center">
-
- 3,234
- </td>
-
- <td align="center">
-
- 3,266
- </td>
-
- <td align="center">
-
- 3,033
- </td>
-
- <td align="center">
-
- 3,603
- </td>
-
- <td align="center">
-
- 4,511
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 4,038
- </td>
-
- <td align="center">
-
- 3,272
- </td>
-
- <td align="center">
-
- 3,316
- </td>
-
- <td align="center">
-
- 2,909
- </td>
-
- <td align="center">
-
- 3,057
- </td>
-
- <td align="center">
-
- 4,081
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,661
- </td>
-
- <td align="center">
-
- 3,359
- </td>
-
- <td align="center">
-
- 3,062
- </td>
-
- <td align="center">
-
- 3,354
- </td>
-
- <td align="center">
-
- 4,215
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,942
- </td>
-
- <td align="center">
-
- 3,417
- </td>
-
- <td align="center">
-
- 3,077
- </td>
-
- <td align="center">
-
- 3,395
- </td>
-
- <td align="center">
-
- 4,139
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,703
- </td>
-
- <td align="center">
-
- 3,169
- </td>
-
- <td align="center">
-
- 3,095
- </td>
-
- <td align="center">
-
- 3,100
- </td>
-
- <td align="center">
-
- 3,752
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,727
- </td>
-
- <td align="center">
-
- 3,469
- </td>
-
- <td align="center">
-
- 3,179
- </td>
-
- <td align="center">
-
- 3,375
- </td>
-
- <td align="center">
-
- 3,874
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,722
- </td>
-
- <td align="center">
-
- 3,145
- </td>
-
- <td align="center">
-
- 3,159
- </td>
-
- <td align="center">
-
- 3,213
- </td>
-
- <td align="center">
-
- 3,567
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
-
- </td>
-
- <td align="center">
-
- 3,866
- </td>
-
- <td align="center">
-
- 3,251
- </td>
-
- <td align="center">
-
- 3,199
- </td>
-
- <td align="center">
-
- 3,324
- </td>
-
- <td align="center">
-
- 3,362
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 23,482
- </td>
-
- <td align="center">
-
- 41,997
- </td>
-
- <td align="center">
-
- 38,946
- </td>
-
- <td align="center">
-
- 37,148
- </td>
-
- <td align="center">
-
- 40,601
- </td>
-
- <td align="center">
-
- 49,764
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Movement Statistics(2002-2007) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2007</th>
-
- <th align="center">2006</th>
-
- <th align="center">2005</th>
-
- <th align="center">2004</th>
-
- <th align="center">2003</th>
-
- <th align="center">2002</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 4,384
- </td>
-
- <td align="center">
-
- 3,933
- </td>
-
- <td align="center">
-
- 3,528
- </td>
-
- <td align="center">
-
- 3,051
- </td>
-
- <td align="center">
-
- 3,257
- </td>
-
- <td align="center">
-
- 2,711
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 4,131
- </td>
-
- <td align="center">
-
- 3,667
- </td>
-
- <td align="center">
-
- 3,331
- </td>
-
- <td align="center">
-
- 2,372
- </td>
-
- <td align="center">
-
- 3,003
- </td>
-
- <td align="center">
-
- 2,747
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 4,349
- </td>
-
- <td align="center">
-
- 4,345
- </td>
-
- <td align="center">
-
- 3,549
- </td>
-
- <td align="center">
-
- 3,049
- </td>
-
- <td align="center">
-
- 3,109
- </td>
-
- <td align="center">
-
- 2,985
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 4,460
- </td>
-
- <td align="center">
-
- 4,490
- </td>
-
- <td align="center">
-
- 3,832
- </td>
-
- <td align="center">
-
- 3,359
- </td>
-
- <td align="center">
-
- 2,033
- </td>
-
- <td align="center">
-
- 2,928
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 4,629
- </td>
-
- <td align="center">
-
- 4,245
- </td>
-
- <td align="center">
-
- 3,663
- </td>
-
- <td align="center">
-
- 3,251
- </td>
-
- <td align="center">
-
- 1,229
- </td>
-
- <td align="center">
-
- 3,109
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 4,365
- </td>
-
- <td align="center">
-
- 4,124
- </td>
-
- <td align="center">
-
- 3,752
- </td>
-
- <td align="center">
-
- 3,414
- </td>
-
- <td align="center">
-
- 1,217
- </td>
-
- <td align="center">
-
- 3,049
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
- 4,612
- </td>
-
- <td align="center">
-
- 4,386
- </td>
-
- <td align="center">
-
- 3,876
- </td>
-
- <td align="center">
-
- 3,664
- </td>
-
- <td align="center">
-
- 2,423
- </td>
-
- <td align="center">
-
- 3,078
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
- 4,446
- </td>
-
- <td align="center">
-
- 4,373
- </td>
-
- <td align="center">
-
- 3,987
- </td>
-
- <td align="center">
-
- 3,631
- </td>
-
- <td align="center">
-
- 3,040
- </td>
-
- <td align="center">
-
- 3,166
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
- 4,414
- </td>
-
- <td align="center">
-
- 4,311
- </td>
-
- <td align="center">
-
- 3,782
- </td>
-
- <td align="center">
-
- 3,514
- </td>
-
- <td align="center">
-
- 2,809
- </td>
-
- <td align="center">
-
- 3,239
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
- 4,445
- </td>
-
- <td align="center">
-
- 4,455
- </td>
-
- <td align="center">
-
- 3,898
- </td>
-
- <td align="center">
-
- 3,744
- </td>
-
- <td align="center">
-
- 3,052
- </td>
-
- <td align="center">
-
- 3,562
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 4,563
- </td>
-
- <td align="center">
-
- 4,285
- </td>
-
- <td align="center">
-
- 3,951
- </td>
-
- <td align="center">
-
- 3,694
- </td>
-
- <td align="center">
-
- 3,125
- </td>
-
- <td align="center">
-
- 3,546
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 4,588
- </td>
-
- <td align="center">
-
- 4,435
- </td>
-
- <td align="center">
-
- 3,855
- </td>
-
- <td align="center">
-
- 3,763
- </td>
-
- <td align="center">
-
- 2,996
- </td>
-
- <td align="center">
-
- 3,444
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 53,386
- </td>
-
- <td align="center">
-
- 51,049
- </td>
-
- <td align="center">
-
- 45,004
- </td>
-
- <td align="center">
-
- 40,506
- </td>
-
- <td align="center">
-
- 31,293
- </td>
-
- <td align="center">
-
- 37,564
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Movement Statistics(1996-2001) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">2001</th>
-
- <th align="center">2000</th>
-
- <th align="center">1999</th>
-
- <th align="center">1998</th>
-
- <th align="center">1997</th>
-
- <th align="center">1996</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
- 2,694
- </td>
-
- <td align="center">
-
- 2,201
- </td>
-
- <td align="center">
-
- 1,835
- </td>
-
- <td align="center">
-
- 2,177
- </td>
-
- <td align="center">
-
- 1,353
- </td>
-
- <td align="center">
-
- 744
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
- 2,364
- </td>
-
- <td align="center">
-
- 2,357
- </td>
-
- <td align="center">
-
- 1,826
- </td>
-
- <td align="center">
-
- 1,740
- </td>
-
- <td align="center">
-
- 1,339
- </td>
-
- <td align="center">
-
- 692
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
- 2,543
- </td>
-
- <td align="center">
-
- 2,206
- </td>
-
- <td align="center">
-
- 1,895
- </td>
-
- <td align="center">
-
- 1,911
- </td>
-
- <td align="center">
-
- 1,533
- </td>
-
- <td align="center">
-
- 872
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
- 2,531
- </td>
-
- <td align="center">
-
- 2,311
- </td>
-
- <td align="center">
-
- 2,076
- </td>
-
- <td align="center">
-
- 1,886
- </td>
-
- <td align="center">
-
- 1,587
- </td>
-
- <td align="center">
-
- 1,026
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
- 2,579
- </td>
-
- <td align="center">
-
- 2,383
- </td>
-
- <td align="center">
-
- 1,914
- </td>
-
- <td align="center">
-
- 2,102
- </td>
-
- <td align="center">
-
- 1,720
- </td>
-
- <td align="center">
-
- 1,115
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
- 2,681
- </td>
-
- <td align="center">
-
- 2,370
- </td>
-
- <td align="center">
-
- 1,890
- </td>
-
- <td align="center">
-
- 2,038
- </td>
-
- <td align="center">
-
- 1,716
- </td>
-
- <td align="center">
-
- 1,037
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
- 2,903
- </td>
-
- <td align="center">
-
- 2,609
- </td>
-
- <td align="center">
-
- 1,916
- </td>
-
- <td align="center">
-
- 2,078
- </td>
-
- <td align="center">
-
- 1,693
- </td>
-
- <td align="center">
-
- 1,209
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
- 3,037
- </td>
-
- <td align="center">
-
- 2,487
- </td>
-
- <td align="center">
-
- 1,968
- </td>
-
- <td align="center">
-
- 2,061
- </td>
-
- <td align="center">
-
- 1,676
- </td>
-
- <td align="center">
-
- 1,241
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
- 2,767
- </td>
-
- <td align="center">
-
- 2,329
- </td>
-
- <td align="center">
-
- 1,955
- </td>
-
- <td align="center">
-
- 1,970
- </td>
-
- <td align="center">
-
- 1,681
- </td>
-
- <td align="center">
-
- 1,263
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
- 2,922
- </td>
-
- <td align="center">
-
- 2,417
- </td>
-
- <td align="center">
-
- 2,267
- </td>
-
- <td align="center">
-
- 1,969
- </td>
-
- <td align="center">
-
- 1,809
- </td>
-
- <td align="center">
-
- 1,368
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 2,670
- </td>
-
- <td align="center">
-
- 2,273
- </td>
-
- <td align="center">
-
- 2,132
- </td>
-
- <td align="center">
-
- 2,102
- </td>
-
- <td align="center">
-
- 1,786
- </td>
-
- <td align="center">
-
- 1,433
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 2,815
- </td>
-
- <td align="center">
-
- 2,749
- </td>
-
- <td align="center">
-
- 2,187
- </td>
-
- <td align="center">
-
- 1,981
- </td>
-
- <td align="center">
-
- 1,944
- </td>
-
- <td align="center">
-
- 1,386
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 32,506
- </td>
-
- <td align="center">
-
- 28,692
- </td>
-
- <td align="center">
-
- 23,861
- </td>
-
- <td align="center">
-
- 24,015
- </td>
-
- <td align="center">
-
- 19,837
- </td>
-
- <td align="center">
-
- 13,386
- </td>
-
- </tr>
- </tbody>
- </table>
-
- <br><br><br>
- <span id="title">Movement Statistics(1995-1995) </span><br><br>
- <table class="style1">
- <tbody>
- <tr height="17">
- <th align="right"> </th>
-
- <th align="center">1995</th>
-
- </tr>
- <tr height="17">
- <th align="right">January</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">February</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">March</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">April</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">May</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">June</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">July</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">August</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">September</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">October</th>
-
- <td align="center">
-
-
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">November</th>
-
- <td align="center">
-
- 126
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">December</th>
-
- <td align="center">
-
- 536
- </td>
-
- </tr>
- <tr height="17">
- <th align="right">Total</th>
-
- <td align="center">
-
- 662
- </td>
-
- </tr>
- </tbody>
- </table>
-
-
- <br><br><br>
- <div align="right"><img src="./macau_files/mov_stat.jpg" alt="passenger statistic picture" width="565" height="318"></div>
-
-
- </div>
-
- </div>
- </div>
- </div>
-
-
- <!--/*end context*/-->
- </div>
- </div>
-
- <div id="buttombar"><img height="100" src="./macau_files/buttombar.gif"></div>
- <div id="logo">
-
-
-
- <div>
-
- <a href="http://www.macau-airport.com/envirop/zh/default.php" style="display: inline;"><img height="80" src="./macau_files/38.jpg"></a>
-
- </div>
-
-
- <div>
-
- <a href="http://www.macau-airport.com/envirop/en/default.php" style="display: inline;"><img height="80" src="./macau_files/36.jpg"></a>
-
- </div>
-
-</div>
-</div>
-
-
-
-</div>
-
-
-<div id="footer">
-<hr>
- <div id="footer-left">
- <a href="http://www.camacau.com/index">Main Page</a> |
- <a href="http://www.camacau.com/geographic_information">Our Business</a> |
- <a href="http://www.camacau.com/about_us">About Us</a> |
- <a href="http://www.camacau.com/pressReleases_list">Media Centre</a> |
- <a href="http://www.camacau.com/rlinks2">Related Links</a> |
- <a href="http://www.camacau.com/download_list">Interactive</a>
- </div>
- <div id="footer-right">Macau International Airport Co. Ltd. | Copyright 2013 | All rights reserved</div>
-</div>
-</div>
-</div>
-
-<div id="___fireplug_chrome_extension___" style="display: none;"></div><iframe id="rdbIndicator" width="100%" height="270" border="0" src="./macau_files/indicator.html" style="display: none; border: 0; position: fixed; left: 0; top: 0; z-index: 2147483647"></iframe><link rel="stylesheet" type="text/css" media="screen" href="chrome-extension://fcdjadjbdihbaodagojiomdljhjhjfho/css/atd.css"></body></html>
\ No newline at end of file
diff --git a/pandas/tests/io/data/html/nyse_wsj.html b/pandas/tests/io/data/html/nyse_wsj.html
deleted file mode 100644
index 2360bd49e9950..0000000000000
--- a/pandas/tests/io/data/html/nyse_wsj.html
+++ /dev/null
@@ -1,1207 +0,0 @@
-<table border="0" cellpadding="0" cellspacing="0" class="autocompleteContainer">
- <tbody>
- <tr>
- <td>
- <div class="symbolCompleteContainer">
- <div><input autocomplete="off" maxlength="80" name="KEYWORDS" type="text" value=""/></div>
- </div>
- <div class="hat_button">
- <span class="hat_button_text">SEARCH</span>
- </div>
- <div style="clear: both;"><div class="subSymbolCompleteResults"></div></div>
- </td>
- </tr>
- </tbody>
-</table>
-<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr>
- <td height="0"><img alt="" border="0" height="0" src="null/img/b.gif" width="1"/></td>
-</tr></tbody></table>
-<table border="0" cellpadding="0" cellspacing="0" class="mdcTable" width="100%">
- <tbody><tr>
- <td class="colhead" style="text-align:left"> </td>
- <td class="colhead" style="text-align:left">Issue<span class="textb10gray" style="margin-left: 8px;">(Roll over for charts and headlines)</span>
- </td>
- <td class="colhead">Volume</td>
- <td class="colhead">Price</td>
- <td class="colhead" style="width:35px;">Chg</td>
- <td class="colhead">% Chg</td>
- </tr>
- <tr>
- <td class="num">1</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=JCP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'JCP')">J.C. Penney (JCP)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">250,697,455</td>
- <td class="nnum">$9.05</td>
- <td class="nnum">-1.37</td>
- <td class="nnum" style="border-right:0px">-13.15</td>
- </tr>
- <tr>
- <td class="num">2</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=BAC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BAC')">Bank of America (BAC)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">77,162,103</td>
- <td class="nnum">13.90</td>
- <td class="nnum">-0.18</td>
- <td class="nnum" style="border-right:0px">-1.28</td>
- </tr>
- <tr>
- <td class="num">3</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=RAD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RAD')">Rite Aid (RAD)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">52,140,382</td>
- <td class="nnum">4.70</td>
- <td class="nnum">-0.08</td>
- <td class="nnum" style="border-right:0px">-1.67</td>
- </tr>
- <tr>
- <td class="num">4</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=F" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'F')">Ford Motor (F)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">33,745,287</td>
- <td class="nnum">17.05</td>
- <td class="nnum">-0.22</td>
- <td class="nnum" style="border-right:0px">-1.27</td>
- </tr>
- <tr>
- <td class="num">5</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=PFE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PFE')">Pfizer (PFE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">27,801,853</td>
- <td class="pnum">28.88</td>
- <td class="pnum">0.36</td>
- <td class="pnum" style="border-right:0px">1.26</td>
- </tr>
- <tr>
- <td class="num">6</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=HTZ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HTZ')">Hertz Global Hldgs (HTZ)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">25,821,264</td>
- <td class="pnum">22.32</td>
- <td class="pnum">0.69</td>
- <td class="pnum" style="border-right:0px">3.19</td>
- </tr>
- <tr>
- <td class="num">7</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=GE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GE')">General Electric (GE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">25,142,064</td>
- <td class="nnum">24.05</td>
- <td class="nnum">-0.20</td>
- <td class="nnum" style="border-right:0px">-0.82</td>
- </tr>
- <tr>
- <td class="num">8</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ELN" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ELN')">Elan ADS (ELN)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">24,725,209</td>
- <td class="pnum">15.59</td>
- <td class="pnum">0.08</td>
- <td class="pnum" style="border-right:0px">0.52</td>
- </tr>
- <tr>
- <td class="num">9</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=JPM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'JPM')">JPMorgan Chase (JPM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">22,402,756</td>
- <td class="pnum">52.24</td>
- <td class="pnum">0.35</td>
- <td class="pnum" style="border-right:0px">0.67</td>
- </tr>
- <tr>
- <td class="num">10</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=RF" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RF')">Regions Financial (RF)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">20,790,532</td>
- <td class="pnum">9.30</td>
- <td class="pnum">0.12</td>
- <td class="pnum" style="border-right:0px">1.31</td>
- </tr>
- <tr>
- <td class="num">11</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=VMEM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VMEM')">Violin Memory (VMEM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">20,669,846</td>
- <td class="nnum">7.02</td>
- <td class="nnum">-1.98</td>
- <td class="nnum" style="border-right:0px">-22.00</td>
- </tr>
- <tr>
- <td class="num">12</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=C" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'C')">Citigroup (C)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">19,979,932</td>
- <td class="nnum">48.89</td>
- <td class="nnum">-0.04</td>
- <td class="nnum" style="border-right:0px">-0.08</td>
- </tr>
- <tr>
- <td class="num">13</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=NOK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NOK')">Nokia ADS (NOK)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">19,585,075</td>
- <td class="pnum">6.66</td>
- <td class="pnum">0.02</td>
- <td class="pnum" style="border-right:0px">0.30</td>
- </tr>
- <tr>
- <td class="num">14</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=WFC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WFC')">Wells Fargo (WFC)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">19,478,590</td>
- <td class="nnum">41.59</td>
- <td class="nnum">-0.02</td>
- <td class="nnum" style="border-right:0px">-0.05</td>
- </tr>
- <tr>
- <td class="num">15</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=VALE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VALE')">Vale ADS (VALE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">18,781,987</td>
- <td class="nnum">15.60</td>
- <td class="nnum">-0.52</td>
- <td class="nnum" style="border-right:0px">-3.23</td>
- </tr>
- <tr>
- <td class="num">16</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=DAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'DAL')">Delta Air Lines (DAL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">16,013,956</td>
- <td class="nnum">23.57</td>
- <td class="nnum">-0.44</td>
- <td class="nnum" style="border-right:0px">-1.83</td>
- </tr>
- <tr>
- <td class="num">17</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=EMC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'EMC')">EMC (EMC)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">15,771,252</td>
- <td class="nnum">26.07</td>
- <td class="nnum">-0.11</td>
- <td class="nnum" style="border-right:0px">-0.42</td>
- </tr>
- <tr>
- <td class="num">18</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=NKE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NKE')">Nike Cl B (NKE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">15,514,717</td>
- <td class="pnum">73.64</td>
- <td class="pnum">3.30</td>
- <td class="pnum" style="border-right:0px">4.69</td>
- </tr>
- <tr>
- <td class="num">19</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=AA" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AA')">Alcoa (AA)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">14,061,073</td>
- <td class="nnum">8.20</td>
- <td class="nnum">-0.07</td>
- <td class="nnum" style="border-right:0px">-0.85</td>
- </tr>
- <tr>
- <td class="num">20</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=GM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GM')">General Motors (GM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">13,984,004</td>
- <td class="nnum">36.37</td>
- <td class="nnum">-0.58</td>
- <td class="nnum" style="border-right:0px">-1.57</td>
- </tr>
- <tr>
- <td class="num">21</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ORCL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ORCL')">Oracle (ORCL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">13,856,671</td>
- <td class="nnum">33.78</td>
- <td class="nnum">-0.03</td>
- <td class="nnum" style="border-right:0px">-0.09</td>
- </tr>
- <tr>
- <td class="num">22</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=T" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'T')">AT&T (T)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">13,736,948</td>
- <td class="nnum">33.98</td>
- <td class="nnum">-0.25</td>
- <td class="nnum" style="border-right:0px">-0.73</td>
- </tr>
- <tr>
- <td class="num">23</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=TSL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TSL')">Trina Solar ADS (TSL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">13,284,202</td>
- <td class="pnum">14.83</td>
- <td class="pnum">1.99</td>
- <td class="pnum" style="border-right:0px">15.50</td>
- </tr>
- <tr>
- <td class="num">24</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=YGE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'YGE')">Yingli Green Energy Holding ADS (YGE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">12,978,378</td>
- <td class="pnum">6.73</td>
- <td class="pnum">0.63</td>
- <td class="pnum" style="border-right:0px">10.33</td>
- </tr>
- <tr>
- <td class="num">25</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=PBR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PBR')">Petroleo Brasileiro ADS (PBR)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">12,833,660</td>
- <td class="nnum">15.40</td>
- <td class="nnum">-0.21</td>
- <td class="nnum" style="border-right:0px">-1.35</td>
- </tr>
- <tr>
- <td class="num">26</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=UAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'UAL')">United Continental Holdings (UAL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">12,603,225</td>
- <td class="nnum">30.91</td>
- <td class="nnum">-3.16</td>
- <td class="nnum" style="border-right:0px">-9.28</td>
- </tr>
- <tr>
- <td class="num">27</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=KO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KO')">Coca-Cola (KO)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">12,343,452</td>
- <td class="nnum">38.40</td>
- <td class="nnum">-0.34</td>
- <td class="nnum" style="border-right:0px">-0.88</td>
- </tr>
- <tr>
- <td class="num">28</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ACI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ACI')">Arch Coal (ACI)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">12,261,138</td>
- <td class="nnum">4.25</td>
- <td class="nnum">-0.28</td>
- <td class="nnum" style="border-right:0px">-6.18</td>
- </tr>
- <tr>
- <td class="num">29</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MS')">Morgan Stanley (MS)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,956,345</td>
- <td class="nnum">27.08</td>
- <td class="nnum">-0.07</td>
- <td class="nnum" style="border-right:0px">-0.26</td>
- </tr>
- <tr>
- <td class="num">30</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=P" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'P')">Pandora Media (P)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,829,963</td>
- <td class="pnum">25.52</td>
- <td class="pnum">0.13</td>
- <td class="pnum" style="border-right:0px">0.51</td>
- </tr>
- <tr>
- <td class="num">31</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ABX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABX')">Barrick Gold (ABX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,775,585</td>
- <td class="num">18.53</td>
- <td class="num">0.00</td>
- <td class="num" style="border-right:0px">0.00</td>
- </tr>
- <tr>
- <td class="num">32</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ABT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABT')">Abbott Laboratories (ABT)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,755,718</td>
- <td class="nnum">33.14</td>
- <td class="nnum">-0.52</td>
- <td class="nnum" style="border-right:0px">-1.54</td>
- </tr>
- <tr>
- <td class="num">33</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=BSBR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BSBR')">Banco Santander Brasil ADS (BSBR)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,587,310</td>
- <td class="pnum">7.01</td>
- <td class="pnum">0.46</td>
- <td class="pnum" style="border-right:0px">7.02</td>
- </tr>
- <tr>
- <td class="num">34</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=AMD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AMD')">Advanced Micro Devices (AMD)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,337,609</td>
- <td class="nnum">3.86</td>
- <td class="nnum">-0.03</td>
- <td class="nnum" style="border-right:0px">-0.77</td>
- </tr>
- <tr>
- <td class="num">35</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=NLY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NLY')">Annaly Capital Management (NLY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">11,004,440</td>
- <td class="nnum">11.63</td>
- <td class="nnum">-0.07</td>
- <td class="nnum" style="border-right:0px">-0.60</td>
- </tr>
- <tr>
- <td class="num">36</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ANR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ANR')">Alpha Natural Resources (ANR)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,941,074</td>
- <td class="nnum">6.08</td>
- <td class="nnum">-0.19</td>
- <td class="nnum" style="border-right:0px">-3.03</td>
- </tr>
- <tr>
- <td class="num">37</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=XOM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'XOM')">Exxon Mobil (XOM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,668,115</td>
- <td class="nnum">86.90</td>
- <td class="nnum">-0.17</td>
- <td class="nnum" style="border-right:0px">-0.20</td>
- </tr>
- <tr>
- <td class="num">38</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ITUB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ITUB')">Itau Unibanco Holding ADS (ITUB)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,638,803</td>
- <td class="pnum">14.30</td>
- <td class="pnum">0.23</td>
- <td class="pnum" style="border-right:0px">1.63</td>
- </tr>
- <tr>
- <td class="num">39</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MRK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MRK')">Merck&Co (MRK)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,388,152</td>
- <td class="pnum">47.79</td>
- <td class="pnum">0.11</td>
- <td class="pnum" style="border-right:0px">0.23</td>
- </tr>
- <tr>
- <td class="num">40</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ALU" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ALU')">Alcatel-Lucent ADS (ALU)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,181,833</td>
- <td class="pnum">3.65</td>
- <td class="pnum">0.01</td>
- <td class="pnum" style="border-right:0px">0.27</td>
- </tr>
- <tr>
- <td class="num">41</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=VZ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VZ')">Verizon Communications (VZ)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,139,321</td>
- <td class="nnum">47.00</td>
- <td class="nnum">-0.67</td>
- <td class="nnum" style="border-right:0px">-1.41</td>
- </tr>
- <tr>
- <td class="num">42</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MHR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MHR')">Magnum Hunter Resources (MHR)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">10,004,303</td>
- <td class="pnum">6.33</td>
- <td class="pnum">0.46</td>
- <td class="pnum" style="border-right:0px">7.84</td>
- </tr>
- <tr>
- <td class="num">43</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=HPQ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HPQ')">Hewlett-Packard (HPQ)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,948,935</td>
- <td class="nnum">21.17</td>
- <td class="nnum">-0.13</td>
- <td class="nnum" style="border-right:0px">-0.61</td>
- </tr>
- <tr>
- <td class="num">44</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=PHM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PHM')">PulteGroup (PHM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,899,141</td>
- <td class="nnum">16.57</td>
- <td class="nnum">-0.41</td>
- <td class="nnum" style="border-right:0px">-2.41</td>
- </tr>
- <tr>
- <td class="num">45</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SOL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SOL')">ReneSola ADS (SOL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,667,438</td>
- <td class="pnum">4.84</td>
- <td class="pnum">0.39</td>
- <td class="pnum" style="border-right:0px">8.76</td>
- </tr>
- <tr>
- <td class="num">46</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=GLW" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GLW')">Corning (GLW)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,547,265</td>
- <td class="nnum">14.73</td>
- <td class="nnum">-0.21</td>
- <td class="nnum" style="border-right:0px">-1.41</td>
- </tr>
- <tr>
- <td class="num">47</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=COLE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'COLE')">Cole Real Estate Investments (COLE)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,544,021</td>
- <td class="pnum">12.21</td>
- <td class="pnum">0.01</td>
- <td class="pnum" style="border-right:0px">0.08</td>
- </tr>
- <tr>
- <td class="num">48</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=DOW" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'DOW')">Dow Chemical (DOW)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,150,479</td>
- <td class="nnum">39.02</td>
- <td class="nnum">-0.97</td>
- <td class="nnum" style="border-right:0px">-2.43</td>
- </tr>
- <tr>
- <td class="num">49</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=IGT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IGT')">International Game Technology (IGT)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">9,129,123</td>
- <td class="nnum">19.23</td>
- <td class="nnum">-1.44</td>
- <td class="nnum" style="border-right:0px">-6.97</td>
- </tr>
- <tr>
- <td class="num">50</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ACN" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ACN')">Accenture Cl A (ACN)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,773,260</td>
- <td class="nnum">74.09</td>
- <td class="nnum">-1.78</td>
- <td class="nnum" style="border-right:0px">-2.35</td>
- </tr>
- <tr>
- <td class="num">51</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=KEY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KEY')">KeyCorp (KEY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,599,333</td>
- <td class="pnum">11.36</td>
- <td class="pnum">0.02</td>
- <td class="pnum" style="border-right:0px">0.18</td>
- </tr>
- <tr>
- <td class="num">52</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=BMY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BMY')">Bristol-Myers Squibb (BMY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,440,709</td>
- <td class="nnum">46.20</td>
- <td class="nnum">-0.73</td>
- <td class="nnum" style="border-right:0px">-1.56</td>
- </tr>
- <tr>
- <td class="num">53</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SID" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SID')">Companhia Siderurgica Nacional ADS (SID)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,437,636</td>
- <td class="nnum">4.36</td>
- <td class="nnum">-0.05</td>
- <td class="nnum" style="border-right:0px">-1.13</td>
- </tr>
- <tr>
- <td class="num">54</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=HRB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HRB')">H&R Block (HRB)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,240,984</td>
- <td class="pnum">26.36</td>
- <td class="pnum">0.31</td>
- <td class="pnum" style="border-right:0px">1.19</td>
- </tr>
- <tr>
- <td class="num">55</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MTG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MTG')">MGIC Investment (MTG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,135,037</td>
- <td class="nnum">7.26</td>
- <td class="nnum">-0.10</td>
- <td class="nnum" style="border-right:0px">-1.36</td>
- </tr>
- <tr>
- <td class="num">56</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=RNG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RNG')">RingCentral Cl A (RNG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,117,469</td>
- <td class="pnum">18.20</td>
- <td class="pnum">5.20</td>
- <td class="pnum" style="border-right:0px">40.00</td>
- </tr>
- <tr>
- <td class="num">57</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=X" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'X')">United States Steel (X)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,107,899</td>
- <td class="nnum">20.44</td>
- <td class="nnum">-0.66</td>
- <td class="nnum" style="border-right:0px">-3.13</td>
- </tr>
- <tr>
- <td class="num">58</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CLF" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CLF')">Cliffs Natural Resources (CLF)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,041,572</td>
- <td class="nnum">21.00</td>
- <td class="nnum">-0.83</td>
- <td class="nnum" style="border-right:0px">-3.80</td>
- </tr>
- <tr>
- <td class="num">59</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=NEM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NEM')">Newmont Mining (NEM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">8,014,250</td>
- <td class="nnum">27.98</td>
- <td class="nnum">-0.19</td>
- <td class="nnum" style="border-right:0px">-0.67</td>
- </tr>
- <tr>
- <td class="num">60</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MO')">Altria Group (MO)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,786,048</td>
- <td class="nnum">34.71</td>
- <td class="nnum">-0.29</td>
- <td class="nnum" style="border-right:0px">-0.83</td>
- </tr>
- <tr>
- <td class="num">61</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SD')">SandRidge Energy (SD)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,782,745</td>
- <td class="nnum">5.93</td>
- <td class="nnum">-0.06</td>
- <td class="nnum" style="border-right:0px">-1.00</td>
- </tr>
- <tr>
- <td class="num">62</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MCP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MCP')">Molycorp (MCP)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,735,831</td>
- <td class="nnum">6.73</td>
- <td class="nnum">-0.45</td>
- <td class="nnum" style="border-right:0px">-6.27</td>
- </tr>
- <tr>
- <td class="num">63</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=HAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HAL')">Halliburton (HAL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,728,735</td>
- <td class="nnum">48.39</td>
- <td class="nnum">-0.32</td>
- <td class="nnum" style="border-right:0px">-0.66</td>
- </tr>
- <tr>
- <td class="num">64</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=TSM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TSM')">Taiwan Semiconductor Manufacturing ADS (TSM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,661,397</td>
- <td class="nnum">17.07</td>
- <td class="nnum">-0.25</td>
- <td class="nnum" style="border-right:0px">-1.44</td>
- </tr>
- <tr>
- <td class="num">65</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=FCX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'FCX')">Freeport-McMoRan Copper&Gold (FCX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,622,803</td>
- <td class="nnum">33.42</td>
- <td class="nnum">-0.45</td>
- <td class="nnum" style="border-right:0px">-1.33</td>
- </tr>
- <tr>
- <td class="num">66</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=KOG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KOG')">Kodiak Oil&Gas (KOG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,543,806</td>
- <td class="pnum">11.94</td>
- <td class="pnum">0.16</td>
- <td class="pnum" style="border-right:0px">1.36</td>
- </tr>
- <tr>
- <td class="num">67</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=XRX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'XRX')">Xerox (XRX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,440,689</td>
- <td class="nnum">10.37</td>
- <td class="nnum">-0.01</td>
- <td class="nnum" style="border-right:0px">-0.10</td>
- </tr>
- <tr>
- <td class="num">68</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=S" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'S')">Sprint (S)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,291,351</td>
- <td class="nnum">6.16</td>
- <td class="nnum">-0.14</td>
- <td class="nnum" style="border-right:0px">-2.22</td>
- </tr>
- <tr>
- <td class="num">69</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=TWO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TWO')">Two Harbors Investment (TWO)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,153,803</td>
- <td class="pnum">9.79</td>
- <td class="pnum">0.05</td>
- <td class="pnum" style="border-right:0px">0.51</td>
- </tr>
- <tr>
- <td class="num">70</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=WLT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WLT')">Walter Energy (WLT)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,152,192</td>
- <td class="nnum">14.19</td>
- <td class="nnum">-0.36</td>
- <td class="nnum" style="border-right:0px">-2.47</td>
- </tr>
- <tr>
- <td class="num">71</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=IP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IP')">International Paper (IP)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,123,722</td>
- <td class="nnum">45.44</td>
- <td class="nnum">-1.85</td>
- <td class="nnum" style="border-right:0px">-3.91</td>
- </tr>
- <tr>
- <td class="num">72</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=PPL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PPL')">PPL (PPL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">7,026,292</td>
- <td class="nnum">30.34</td>
- <td class="nnum">-0.13</td>
- <td class="nnum" style="border-right:0px">-0.43</td>
- </tr>
- <tr>
- <td class="num">73</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=GG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GG')">Goldcorp (GG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,857,447</td>
- <td class="pnum">25.76</td>
- <td class="pnum">0.08</td>
- <td class="pnum" style="border-right:0px">0.31</td>
- </tr>
- <tr>
- <td class="num">74</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=TWX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TWX')">Time Warner (TWX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,807,237</td>
- <td class="pnum">66.20</td>
- <td class="pnum">1.33</td>
- <td class="pnum" style="border-right:0px">2.05</td>
- </tr>
- <tr>
- <td class="num">75</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SNV" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SNV')">Synovus Financial (SNV)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,764,805</td>
- <td class="pnum">3.29</td>
- <td class="pnum">0.02</td>
- <td class="pnum" style="border-right:0px">0.61</td>
- </tr>
- <tr>
- <td class="num">76</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=AKS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AKS')">AK Steel Holding (AKS)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,662,599</td>
- <td class="nnum">3.83</td>
- <td class="nnum">-0.11</td>
- <td class="nnum" style="border-right:0px">-2.79</td>
- </tr>
- <tr>
- <td class="num">77</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=BSX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BSX')">Boston Scientific (BSX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,629,084</td>
- <td class="nnum">11.52</td>
- <td class="nnum">-0.15</td>
- <td class="nnum" style="border-right:0px">-1.29</td>
- </tr>
- <tr>
- <td class="num">78</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=EGO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'EGO')">Eldorado Gold (EGO)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,596,902</td>
- <td class="nnum">6.65</td>
- <td class="nnum">-0.03</td>
- <td class="nnum" style="border-right:0px">-0.45</td>
- </tr>
- <tr>
- <td class="num">79</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=NR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NR')">Newpark Resources (NR)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,552,453</td>
- <td class="pnum">12.56</td>
- <td class="pnum">0.09</td>
- <td class="pnum" style="border-right:0px">0.72</td>
- </tr>
- <tr>
- <td class="num">80</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=ABBV" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABBV')">AbbVie (ABBV)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,525,524</td>
- <td class="nnum">44.33</td>
- <td class="nnum">-0.67</td>
- <td class="nnum" style="border-right:0px">-1.49</td>
- </tr>
- <tr>
- <td class="num">81</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MBI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MBI')">MBIA (MBI)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,416,587</td>
- <td class="nnum">10.38</td>
- <td class="nnum">-0.43</td>
- <td class="nnum" style="border-right:0px">-3.98</td>
- </tr>
- <tr>
- <td class="num">82</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SAI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SAI')">SAIC (SAI)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,404,587</td>
- <td class="pnum">16.03</td>
- <td class="pnum">0.13</td>
- <td class="pnum" style="border-right:0px">0.82</td>
- </tr>
- <tr>
- <td class="num">83</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=PG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PG')">Procter&Gamble (PG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,389,143</td>
- <td class="nnum">77.21</td>
- <td class="nnum">-0.84</td>
- <td class="nnum" style="border-right:0px">-1.08</td>
- </tr>
- <tr>
- <td class="num">84</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=IAG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IAG')">IAMGOLD (IAG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,293,001</td>
- <td class="nnum">4.77</td>
- <td class="nnum">-0.06</td>
- <td class="nnum" style="border-right:0px">-1.24</td>
- </tr>
- <tr>
- <td class="num">85</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=SWY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SWY')">Safeway (SWY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,268,184</td>
- <td class="nnum">32.25</td>
- <td class="nnum">-0.29</td>
- <td class="nnum" style="border-right:0px">-0.89</td>
- </tr>
- <tr>
- <td class="num">86</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=KGC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KGC')">Kinross Gold (KGC)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">6,112,658</td>
- <td class="nnum">4.99</td>
- <td class="nnum">-0.03</td>
- <td class="nnum" style="border-right:0px">-0.60</td>
- </tr>
- <tr>
- <td class="num">87</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MGM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MGM')">MGM Resorts International (MGM)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,986,143</td>
- <td class="nnum">20.22</td>
- <td class="nnum">-0.05</td>
- <td class="nnum" style="border-right:0px">-0.25</td>
- </tr>
- <tr>
- <td class="num">88</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CX')">Cemex ADS (CX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,907,040</td>
- <td class="nnum">11.27</td>
- <td class="nnum">-0.06</td>
- <td class="nnum" style="border-right:0px">-0.53</td>
- </tr>
- <tr>
- <td class="num">89</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=AIG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AIG')">American International Group (AIG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,900,133</td>
- <td class="nnum">49.15</td>
- <td class="nnum">-0.30</td>
- <td class="nnum" style="border-right:0px">-0.61</td>
- </tr>
- <tr>
- <td class="num">90</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CHK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CHK')">Chesapeake Energy (CHK)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,848,016</td>
- <td class="nnum">26.21</td>
- <td class="nnum">-0.20</td>
- <td class="nnum" style="border-right:0px">-0.76</td>
- </tr>
- <tr>
- <td class="num">91</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=RSH" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RSH')">RadioShack (RSH)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,837,833</td>
- <td class="nnum">3.44</td>
- <td class="nnum">-0.43</td>
- <td class="nnum" style="border-right:0px">-11.11</td>
- </tr>
- <tr>
- <td class="num">92</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=USB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'USB')">U.S. Bancorp (USB)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,814,373</td>
- <td class="nnum">36.50</td>
- <td class="nnum">-0.04</td>
- <td class="nnum" style="border-right:0px">-0.11</td>
- </tr>
- <tr>
- <td class="num">93</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=LLY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'LLY')">Eli Lilly (LLY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,776,991</td>
- <td class="nnum">50.50</td>
- <td class="nnum">-0.54</td>
- <td class="nnum" style="border-right:0px">-1.06</td>
- </tr>
- <tr>
- <td class="num">94</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MET" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MET')">MetLife (MET)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,774,996</td>
- <td class="nnum">47.21</td>
- <td class="nnum">-0.37</td>
- <td class="nnum" style="border-right:0px">-0.78</td>
- </tr>
- <tr>
- <td class="num">95</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=AUY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AUY')">Yamana Gold (AUY)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,742,426</td>
- <td class="pnum">10.37</td>
- <td class="pnum">0.03</td>
- <td class="pnum" style="border-right:0px">0.29</td>
- </tr>
- <tr>
- <td class="num">96</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CBS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CBS')">CBS Cl B (CBS)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,718,858</td>
- <td class="nnum">55.50</td>
- <td class="nnum">-0.06</td>
- <td class="nnum" style="border-right:0px">-0.11</td>
- </tr>
- <tr>
- <td class="num">97</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CSX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CSX')">CSX (CSX)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,710,066</td>
- <td class="nnum">25.85</td>
- <td class="nnum">-0.13</td>
- <td class="nnum" style="border-right:0px">-0.50</td>
- </tr>
- <tr>
- <td class="num">98</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=CCL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CCL')">Carnival (CCL)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,661,325</td>
- <td class="nnum">32.88</td>
- <td class="nnum">-0.05</td>
- <td class="nnum" style="border-right:0px">-0.15</td>
- </tr>
- <tr>
- <td class="num">99</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=MOS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MOS')">Mosaic (MOS)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,595,592</td>
- <td class="nnum">43.43</td>
- <td class="nnum">-0.76</td>
- <td class="nnum" style="border-right:0px">-1.72</td>
- </tr>
- <tr>
- <td class="num">100</td>
- <td class="text" style="max-width:307px">
- <a class="linkb" href="/public/quotes/main.html?symbol=WAG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WAG')">Walgreen (WAG)
- </a>
- </td>
- <td align="right" class="num" style="font-weight:bold;">5,568,310</td>
- <td class="nnum">54.51</td>
- <td class="nnum">-0.22</td>
- <td class="nnum" style="border-right:0px">-0.40</td>
- </tr>
-</tbody></table>
-<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%">
- <tbody><tr><td height="20px"><img alt="" border="0" height="20px" src="/img/b.gif" width="1"/></td></tr>
-</tbody></table>
-<table align="center" bgcolor="#ffffff" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #cfc7b7;margin-bottom:5px;" width="575px">
- <tbody><tr>
- <td bgcolor="#e9e7e0" class="b12" colspan="3" style="padding:3px 0px 3px 0px;"><span class="p10" style="color:#000; float:right">An Advertising Feature </span> PARTNER CENTER</td>
- </tr>
-
- <tr>
- <td align="center" class="p10" style="padding:10px 0px 5px 0px;border-right:1px solid #cfc7b7;" valign="top">
-
-
-
- <script type="text/javascript">
-<!--
- var tempHTML = '';
- var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;';
- if ( isSafari ) {
- tempHTML += '<iframe id="mdc_tradingcenter1" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">';
- } else {
- tempHTML += '<iframe id="mdc_tradingcenter1" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">';
- ListOfIframes.mdc_tradingcenter1= adURL;
- }
- tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;" target="_new">';
- tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>';
- document.write(tempHTML);
- // -->
- </script>
- </td>
-
- <td align="center" class="p10" style="padding:10px 0px 5px 0px;border-right:1px solid #cfc7b7;" valign="top">
-
-
-
- <script type="text/javascript">
-<!--
- var tempHTML = '';
- var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;';
- if ( isSafari ) {
- tempHTML += '<iframe id="mdc_tradingcenter2" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">';
- } else {
- tempHTML += '<iframe id="mdc_tradingcenter2" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">';
- ListOfIframes.mdc_tradingcenter2= adURL;
- }
- tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;" target="_new">';
- tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>';
- document.write(tempHTML);
- // -->
- </script>
- </td>
-
- <td align="center" class="p10" style="padding:10px 0px 5px 0px;" valign="top">
-
-
-
- <script type="text/javascript">
-<!--
- var tempHTML = '';
- var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;';
- if ( isSafari ) {
- tempHTML += '<iframe id="mdc_tradingcenter3" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">';
- } else {
- tempHTML += '<iframe id="mdc_tradingcenter3" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">';
- ListOfIframes.mdc_tradingcenter3= adURL;
- }
- tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;" target="_new">';
- tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>';
- document.write(tempHTML);
- // -->
- </script>
- </td>
-
- </tr>
-
-</tbody></table>
-<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%">
- <tbody><tr><td height="20px"><img alt="" border="0" height="20px" src="/img/b.gif" width="1"/></td></tr>
-</tbody></table>
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index 7a814ce82fd73..b649e394c780b 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -14,7 +14,7 @@
from pandas.errors import ParserError
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv
+from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, read_csv
import pandas._testing as tm
from pandas.io.common import file_path_to_url
@@ -373,32 +373,6 @@ def test_python_docs_table(self):
zz = [df.iloc[0, 0][0:4] for df in dfs]
assert sorted(zz) == sorted(["Repo", "What"])
- @pytest.mark.slow
- def test_thousands_macau_stats(self, datapath):
- all_non_nan_table_index = -2
- macau_data = datapath("io", "data", "html", "macau.html")
- dfs = self.read_html(macau_data, index_col=0, attrs={"class": "style1"})
- df = dfs[all_non_nan_table_index]
-
- assert not any(s.isna().any() for _, s in df.items())
-
- @pytest.mark.slow
- def test_thousands_macau_index_col(self, datapath, request):
- # https://github.com/pandas-dev/pandas/issues/29622
- # This tests fails for bs4 >= 4.8.0 - so handle xfail accordingly
- if self.read_html.keywords.get("flavor") == "bs4" and td.safe_import(
- "bs4", "4.8.0"
- ):
- reason = "fails for bs4 version >= 4.8.0"
- request.node.add_marker(pytest.mark.xfail(reason=reason))
-
- all_non_nan_table_index = -2
- macau_data = datapath("io", "data", "html", "macau.html")
- dfs = self.read_html(macau_data, index_col=0, header=0)
- df = dfs[all_non_nan_table_index]
-
- assert not any(s.isna().any() for _, s in df.items())
-
def test_empty_tables(self):
"""
Make sure that read_html ignores empty tables.
@@ -571,23 +545,6 @@ def test_parse_header_of_non_string_column(self):
tm.assert_frame_equal(result, expected)
- def test_nyse_wsj_commas_table(self, datapath):
- data = datapath("io", "data", "html", "nyse_wsj.html")
- df = self.read_html(data, index_col=0, header=0, attrs={"class": "mdcTable"})[0]
-
- expected = Index(
- [
- "Issue(Roll over for charts and headlines)",
- "Volume",
- "Price",
- "Chg",
- "% Chg",
- ]
- )
- nrows = 100
- assert df.shape[0] == nrows
- tm.assert_index_equal(df.columns, expected)
-
@pytest.mark.slow
def test_banklist_header(self, datapath):
from pandas.io.html import _remove_whitespace
@@ -894,24 +851,23 @@ def test_parse_dates_combine(self):
newdf = DataFrame({"datetime": raw_dates})
tm.assert_frame_equal(newdf, res[0])
- def test_computer_sales_page(self, datapath):
- data = datapath("io", "data", "html", "computer_sales_page.html")
- msg = (
- r"Passed header=\[0,1\] are too many "
- r"rows for this multi_index of columns"
- )
- with pytest.raises(ParserError, match=msg):
- self.read_html(data, header=[0, 1])
-
- data = datapath("io", "data", "html", "computer_sales_page.html")
- assert self.read_html(data, header=[1, 2])
-
def test_wikipedia_states_table(self, datapath):
data = datapath("io", "data", "html", "wikipedia_states.html")
assert os.path.isfile(data), f"{repr(data)} is not a file"
assert os.path.getsize(data), f"{repr(data)} is an empty file"
result = self.read_html(data, "Arizona", header=1)[0]
+ assert result.shape == (60, 12)
+ assert "Unnamed" in result.columns[-1]
assert result["sq mi"].dtype == np.dtype("float64")
+ assert np.allclose(result.loc[0, "sq mi"], 665384.04)
+
+ def test_wikipedia_states_multiindex(self, datapath):
+ data = datapath("io", "data", "html", "wikipedia_states.html")
+ result = self.read_html(data, "Arizona", index_col=0)[0]
+ assert result.shape == (60, 11)
+ assert "Unnamed" in result.columns[-1][1]
+ assert result.columns.nlevels == 2
+ assert np.allclose(result.loc["Alaska", ("Total area[2]", "sq mi")], 665384.04)
def test_parser_error_on_empty_header_row(self):
msg = (
| Backport PR #31146: Remove possibly illegal test data | https://api.github.com/repos/pandas-dev/pandas/pulls/33976 | 2020-05-04T19:57:28Z | 2020-05-04T20:59:49Z | 2020-05-04T20:59:49Z | 2020-05-04T20:59:49Z |
Backport PR #33309 on branch 1.0.x (DOC: include Offset.__call__ to autosummary to fix sphinx warning) | diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst
index fc1c6d6bd6d47..17544cb7a1225 100644
--- a/doc/source/reference/offset_frequency.rst
+++ b/doc/source/reference/offset_frequency.rst
@@ -37,6 +37,7 @@ Methods
DateOffset.onOffset
DateOffset.is_anchored
DateOffset.is_on_offset
+ DateOffset.__call__
BusinessDay
-----------
@@ -69,6 +70,7 @@ Methods
BusinessDay.onOffset
BusinessDay.is_anchored
BusinessDay.is_on_offset
+ BusinessDay.__call__
BusinessHour
------------
@@ -100,6 +102,7 @@ Methods
BusinessHour.onOffset
BusinessHour.is_anchored
BusinessHour.is_on_offset
+ BusinessHour.__call__
CustomBusinessDay
-----------------
@@ -131,6 +134,7 @@ Methods
CustomBusinessDay.onOffset
CustomBusinessDay.is_anchored
CustomBusinessDay.is_on_offset
+ CustomBusinessDay.__call__
CustomBusinessHour
------------------
@@ -162,6 +166,7 @@ Methods
CustomBusinessHour.onOffset
CustomBusinessHour.is_anchored
CustomBusinessHour.is_on_offset
+ CustomBusinessHour.__call__
MonthOffset
-----------
@@ -194,6 +199,7 @@ Methods
MonthOffset.onOffset
MonthOffset.is_anchored
MonthOffset.is_on_offset
+ MonthOffset.__call__
MonthEnd
--------
@@ -226,6 +232,7 @@ Methods
MonthEnd.onOffset
MonthEnd.is_anchored
MonthEnd.is_on_offset
+ MonthEnd.__call__
MonthBegin
----------
@@ -258,6 +265,7 @@ Methods
MonthBegin.onOffset
MonthBegin.is_anchored
MonthBegin.is_on_offset
+ MonthBegin.__call__
BusinessMonthEnd
----------------
@@ -290,6 +298,7 @@ Methods
BusinessMonthEnd.onOffset
BusinessMonthEnd.is_anchored
BusinessMonthEnd.is_on_offset
+ BusinessMonthEnd.__call__
BusinessMonthBegin
------------------
@@ -322,6 +331,7 @@ Methods
BusinessMonthBegin.onOffset
BusinessMonthBegin.is_anchored
BusinessMonthBegin.is_on_offset
+ BusinessMonthBegin.__call__
CustomBusinessMonthEnd
----------------------
@@ -354,6 +364,7 @@ Methods
CustomBusinessMonthEnd.onOffset
CustomBusinessMonthEnd.is_anchored
CustomBusinessMonthEnd.is_on_offset
+ CustomBusinessMonthEnd.__call__
CustomBusinessMonthBegin
------------------------
@@ -386,6 +397,7 @@ Methods
CustomBusinessMonthBegin.onOffset
CustomBusinessMonthBegin.is_anchored
CustomBusinessMonthBegin.is_on_offset
+ CustomBusinessMonthBegin.__call__
SemiMonthOffset
---------------
@@ -418,6 +430,7 @@ Methods
SemiMonthOffset.onOffset
SemiMonthOffset.is_anchored
SemiMonthOffset.is_on_offset
+ SemiMonthOffset.__call__
SemiMonthEnd
------------
@@ -450,6 +463,7 @@ Methods
SemiMonthEnd.onOffset
SemiMonthEnd.is_anchored
SemiMonthEnd.is_on_offset
+ SemiMonthEnd.__call__
SemiMonthBegin
--------------
@@ -482,6 +496,7 @@ Methods
SemiMonthBegin.onOffset
SemiMonthBegin.is_anchored
SemiMonthBegin.is_on_offset
+ SemiMonthBegin.__call__
Week
----
@@ -514,6 +529,7 @@ Methods
Week.onOffset
Week.is_anchored
Week.is_on_offset
+ Week.__call__
WeekOfMonth
-----------
@@ -545,6 +561,7 @@ Methods
WeekOfMonth.onOffset
WeekOfMonth.is_anchored
WeekOfMonth.is_on_offset
+ WeekOfMonth.__call__
LastWeekOfMonth
---------------
@@ -576,6 +593,7 @@ Methods
LastWeekOfMonth.onOffset
LastWeekOfMonth.is_anchored
LastWeekOfMonth.is_on_offset
+ LastWeekOfMonth.__call__
QuarterOffset
-------------
@@ -608,6 +626,7 @@ Methods
QuarterOffset.onOffset
QuarterOffset.is_anchored
QuarterOffset.is_on_offset
+ QuarterOffset.__call__
BQuarterEnd
-----------
@@ -640,6 +659,7 @@ Methods
BQuarterEnd.onOffset
BQuarterEnd.is_anchored
BQuarterEnd.is_on_offset
+ BQuarterEnd.__call__
BQuarterBegin
-------------
@@ -672,6 +692,7 @@ Methods
BQuarterBegin.onOffset
BQuarterBegin.is_anchored
BQuarterBegin.is_on_offset
+ BQuarterBegin.__call__
QuarterEnd
----------
@@ -704,6 +725,7 @@ Methods
QuarterEnd.onOffset
QuarterEnd.is_anchored
QuarterEnd.is_on_offset
+ QuarterEnd.__call__
QuarterBegin
------------
@@ -736,6 +758,7 @@ Methods
QuarterBegin.onOffset
QuarterBegin.is_anchored
QuarterBegin.is_on_offset
+ QuarterBegin.__call__
YearOffset
----------
@@ -768,6 +791,7 @@ Methods
YearOffset.onOffset
YearOffset.is_anchored
YearOffset.is_on_offset
+ YearOffset.__call__
BYearEnd
--------
@@ -800,6 +824,7 @@ Methods
BYearEnd.onOffset
BYearEnd.is_anchored
BYearEnd.is_on_offset
+ BYearEnd.__call__
BYearBegin
----------
@@ -832,6 +857,7 @@ Methods
BYearBegin.onOffset
BYearBegin.is_anchored
BYearBegin.is_on_offset
+ BYearBegin.__call__
YearEnd
-------
@@ -864,6 +890,7 @@ Methods
YearEnd.onOffset
YearEnd.is_anchored
YearEnd.is_on_offset
+ YearEnd.__call__
YearBegin
---------
@@ -896,6 +923,7 @@ Methods
YearBegin.onOffset
YearBegin.is_anchored
YearBegin.is_on_offset
+ YearBegin.__call__
FY5253
------
@@ -929,6 +957,7 @@ Methods
FY5253.onOffset
FY5253.is_anchored
FY5253.is_on_offset
+ FY5253.__call__
FY5253Quarter
-------------
@@ -962,6 +991,7 @@ Methods
FY5253Quarter.is_anchored
FY5253Quarter.is_on_offset
FY5253Quarter.year_has_extra_week
+ FY5253Quarter.__call__
Easter
------
@@ -993,6 +1023,7 @@ Methods
Easter.onOffset
Easter.is_anchored
Easter.is_on_offset
+ Easter.__call__
Tick
----
@@ -1024,6 +1055,7 @@ Methods
Tick.onOffset
Tick.is_anchored
Tick.is_on_offset
+ Tick.__call__
Day
---
@@ -1055,6 +1087,7 @@ Methods
Day.onOffset
Day.is_anchored
Day.is_on_offset
+ Day.__call__
Hour
----
@@ -1086,6 +1119,7 @@ Methods
Hour.onOffset
Hour.is_anchored
Hour.is_on_offset
+ Hour.__call__
Minute
------
@@ -1117,6 +1151,7 @@ Methods
Minute.onOffset
Minute.is_anchored
Minute.is_on_offset
+ Minute.__call__
Second
------
@@ -1148,6 +1183,7 @@ Methods
Second.onOffset
Second.is_anchored
Second.is_on_offset
+ Second.__call__
Milli
-----
@@ -1179,6 +1215,7 @@ Methods
Milli.onOffset
Milli.is_anchored
Milli.is_on_offset
+ Milli.__call__
Micro
-----
@@ -1210,6 +1247,7 @@ Methods
Micro.onOffset
Micro.is_anchored
Micro.is_on_offset
+ Micro.__call__
Nano
----
@@ -1241,6 +1279,7 @@ Methods
Nano.onOffset
Nano.is_anchored
Nano.is_on_offset
+ Nano.__call__
BDay
----
@@ -1277,6 +1316,7 @@ Methods
BDay.is_on_offset
BDay.rollback
BDay.rollforward
+ BDay.__call__
BMonthEnd
---------
@@ -1312,6 +1352,7 @@ Methods
BMonthEnd.is_on_offset
BMonthEnd.rollback
BMonthEnd.rollforward
+ BMonthEnd.__call__
BMonthBegin
-----------
@@ -1347,6 +1388,7 @@ Methods
BMonthBegin.is_on_offset
BMonthBegin.rollback
BMonthBegin.rollforward
+ BMonthBegin.__call__
CBMonthEnd
----------
@@ -1386,6 +1428,7 @@ Methods
CBMonthEnd.is_on_offset
CBMonthEnd.rollback
CBMonthEnd.rollforward
+ CBMonthEnd.__call__
CBMonthBegin
------------
@@ -1425,6 +1468,7 @@ Methods
CBMonthBegin.is_on_offset
CBMonthBegin.rollback
CBMonthBegin.rollforward
+ CBMonthBegin.__call__
CDay
----
@@ -1461,6 +1505,7 @@ Methods
CDay.is_on_offset
CDay.rollback
CDay.rollforward
+ CDay.__call__
.. _api.frequencies:
| Backport PR #33309: DOC: include Offset.__call__ to autosummary to fix sphinx warning | https://api.github.com/repos/pandas-dev/pandas/pulls/33975 | 2020-05-04T18:53:10Z | 2020-05-04T19:56:48Z | 2020-05-04T19:56:48Z | 2020-05-04T19:56:48Z |
Backport PR #33080 on branch 1.0.x (CI troubleshoot azure) | diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 7bcc354f53be0..f8a6aba1b387c 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1,6 +1,7 @@
""" test parquet compat """
import datetime
from distutils.version import LooseVersion
+import locale
import os
from warnings import catch_warnings
@@ -484,6 +485,11 @@ def test_categorical(self, pa):
expected = df.astype(object)
check_round_trip(df, pa, expected=expected)
+ # GH#33077 2020-03-27
+ @pytest.mark.xfail(
+ locale.getlocale()[0] == "zh_CN",
+ reason="dateutil cannot parse e.g. '五, 27 3月 2020 21:45:38 GMT'",
+ )
def test_s3_roundtrip(self, df_compat, s3_resource, pa):
# GH #19134
check_round_trip(df_compat, pa, path="s3://pandas-test/pyarrow.parquet")
| Backport PR #33080: CI troubleshoot azure | https://api.github.com/repos/pandas-dev/pandas/pulls/33973 | 2020-05-04T15:50:43Z | 2020-05-04T16:55:21Z | 2020-05-04T16:55:21Z | 2020-05-04T16:55:22Z |
Backport PR #33566 on branch 1.0.x (CI: Fix jedi deprecation warning for 0.17.0 on IPython) | diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 9263409f7a7f8..18c03cd215e48 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -548,7 +548,18 @@ async def test_tab_complete_warning(self, ip):
code = "import pandas as pd; df = pd.DataFrame()"
await ip.run_code(code)
- with tm.assert_produces_warning(None):
+
+ # TODO: remove it when Ipython updates
+ # GH 33567, jedi version raises Deprecation warning in Ipython
+ import jedi
+
+ if jedi.__version__ < "0.17.0":
+ warning = tm.assert_produces_warning(None)
+ else:
+ warning = tm.assert_produces_warning(
+ DeprecationWarning, check_stacklevel=False
+ )
+ with warning:
with provisionalcompleter("ignore"):
list(ip.Completer.completions("df.", 1))
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 4e3585c0be884..19afe25766241 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -28,7 +28,15 @@ async def test_tab_complete_ipython6_warning(ip):
)
await ip.run_code(code)
- with tm.assert_produces_warning(None):
+ # TODO: remove it when Ipython updates
+ # GH 33567, jedi version raises Deprecation warning in Ipython
+ import jedi
+
+ if jedi.__version__ < "0.17.0":
+ warning = tm.assert_produces_warning(None)
+ else:
+ warning = tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False)
+ with warning:
with provisionalcompleter("ignore"):
list(ip.Completer.completions("rs.", 1))
diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py
index f96d6ddfc357e..901d983b51c02 100644
--- a/pandas/tests/series/test_api.py
+++ b/pandas/tests/series/test_api.py
@@ -501,7 +501,18 @@ async def test_tab_complete_warning(self, ip):
code = "import pandas as pd; s = pd.Series()"
await ip.run_code(code)
- with tm.assert_produces_warning(None):
+
+ # TODO: remove it when Ipython updates
+ # GH 33567, jedi version raises Deprecation warning in Ipython
+ import jedi
+
+ if jedi.__version__ < "0.17.0":
+ warning = tm.assert_produces_warning(None)
+ else:
+ warning = tm.assert_produces_warning(
+ DeprecationWarning, check_stacklevel=False
+ )
+ with warning:
with provisionalcompleter("ignore"):
list(ip.Completer.completions("s.", 1))
| Backport PR #33566: CI: Fix jedi deprecation warning for 0.17.0 on IPython | https://api.github.com/repos/pandas-dev/pandas/pulls/33972 | 2020-05-04T15:46:22Z | 2020-05-04T16:49:24Z | 2020-05-04T16:49:24Z | 2020-05-04T16:49:24Z |
DOC: start 1.0.4 | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 6764fbd736d46..0e0c7492da3be 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -16,6 +16,7 @@ Version 1.0
.. toctree::
:maxdepth: 2
+ v1.0.4
v1.0.3
v1.0.2
v1.0.1
diff --git a/doc/source/whatsnew/v1.0.3.rst b/doc/source/whatsnew/v1.0.3.rst
index 26d06433bda0c..62e6ae5b1c5cc 100644
--- a/doc/source/whatsnew/v1.0.3.rst
+++ b/doc/source/whatsnew/v1.0.3.rst
@@ -26,4 +26,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.0.2..v1.0.3|HEAD
+.. contributors:: v1.0.2..v1.0.3
diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
new file mode 100644
index 0000000000000..fa3ac27eba577
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -0,0 +1,31 @@
+
+.. _whatsnew_104:
+
+What's new in 1.0.4 (May ??, 2020)
+------------------------------------
+
+These are the changes in pandas 1.0.4. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_104.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+-
+-
+
+.. _whatsnew_104.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+-
+-
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.0.3..v1.0.4|HEAD
| NOTE: opened against 1.0.x branch as to not commit to release at this stage.
I think could backport a few PRs moving the whatsnews and only after a release remove from 1.1 whatsnew on master. This gives us the chance to easily abandon the release at any time. | https://api.github.com/repos/pandas-dev/pandas/pulls/33970 | 2020-05-04T15:21:33Z | 2020-05-05T11:26:17Z | 2020-05-05T11:26:17Z | 2020-05-05T12:37:49Z |
Fix expected dtype in test_reindex_with_same_tz | diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index 50983dbd8db22..ec4162f87010f 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -53,7 +53,7 @@ def test_reindex_with_same_tz(self):
expected1 = DatetimeIndex(
expected_list1, dtype="datetime64[ns, UTC]", freq=None,
)
- expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.int64,)
+ expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.dtype("intp"))
tm.assert_index_equal(result1, expected1)
tm.assert_numpy_array_equal(result2, expected2)
| Closes https://github.com/pandas-dev/pandas/issues/33845 | https://api.github.com/repos/pandas-dev/pandas/pulls/33969 | 2020-05-04T14:02:12Z | 2020-05-05T14:18:01Z | 2020-05-05T14:18:00Z | 2020-05-05T14:26:16Z |
CI: Bump numpydev URL | diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index 652438440d3f2..5cb58756a6ac1 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -16,7 +16,7 @@ dependencies:
- pip:
- cython==0.29.16 # GH#34014
- "git+git://github.com/dateutil/dateutil.git"
- - "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com"
+ - "--extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple"
- "--pre"
- "numpy"
- "scipy"
| NumPy and scipy are uploading their wheels to a new URL.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33968 | 2020-05-04T13:02:42Z | 2020-05-11T21:42:29Z | 2020-05-11T21:42:29Z | 2020-05-19T11:02:37Z |
Add nrows to read json. | diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py
index f478bf2aee0ba..a490e250943f5 100644
--- a/asv_bench/benchmarks/io/json.py
+++ b/asv_bench/benchmarks/io/json.py
@@ -53,12 +53,18 @@ def time_read_json_lines(self, index):
def time_read_json_lines_concat(self, index):
concat(read_json(self.fname, orient="records", lines=True, chunksize=25000))
+ def time_read_json_lines_nrows(self, index):
+ read_json(self.fname, orient="records", lines=True, nrows=25000)
+
def peakmem_read_json_lines(self, index):
read_json(self.fname, orient="records", lines=True)
def peakmem_read_json_lines_concat(self, index):
concat(read_json(self.fname, orient="records", lines=True, chunksize=25000))
+ def peakmem_read_json_lines_nrows(self, index):
+ read_json(self.fname, orient="records", lines=True, nrows=15000)
+
class ToJSON(BaseIO):
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 17623b943bf87..2243790a663df 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -289,6 +289,7 @@ Other enhancements
- Make :class:`pandas.core.window.Rolling` and :class:`pandas.core.window.Expanding` iterable(:issue:`11704`)
- Make ``option_context`` a :class:`contextlib.ContextDecorator`, which allows it to be used as a decorator over an entire function (:issue:`34253`).
- :meth:`groupby.transform` now allows ``func`` to be ``pad``, ``backfill`` and ``cumcount`` (:issue:`31269`).
+- :meth:`~pandas.io.json.read_json` now accepts `nrows` parameter. (:issue:`33916`).
- :meth `~pandas.io.gbq.read_gbq` now allows to disable progress bar (:issue:`33360`).
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 72aa8fdd16e6d..b973553a767ba 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -355,14 +355,15 @@ def read_json(
dtype=None,
convert_axes=None,
convert_dates=True,
- keep_default_dates=True,
- numpy=False,
- precise_float=False,
+ keep_default_dates: bool = True,
+ numpy: bool = False,
+ precise_float: bool = False,
date_unit=None,
encoding=None,
- lines=False,
- chunksize=None,
+ lines: bool = False,
+ chunksize: Optional[int] = None,
compression="infer",
+ nrows: Optional[int] = None,
):
"""
Convert a JSON string to pandas object.
@@ -493,6 +494,7 @@ def read_json(
for more information on ``chunksize``.
This can only be passed if `lines=True`.
If this is None, the file will be read into memory all at once.
+
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use
gzip, bz2, zip or xz if path_or_buf is a string ending in
@@ -500,6 +502,13 @@ def read_json(
otherwise. If using 'zip', the ZIP file must contain only one data
file to be read in. Set to None for no decompression.
+ nrows : int, optional
+ The number of lines from the line-delimited jsonfile that has to be read.
+ This can only be passed if `lines=True`.
+ If this is None, all the rows will be returned.
+
+ .. versionadded:: 1.1
+
Returns
-------
Series or DataFrame
@@ -600,6 +609,7 @@ def read_json(
lines=lines,
chunksize=chunksize,
compression=compression,
+ nrows=nrows,
)
if chunksize:
@@ -629,14 +639,15 @@ def __init__(
dtype,
convert_axes,
convert_dates,
- keep_default_dates,
- numpy,
- precise_float,
+ keep_default_dates: bool,
+ numpy: bool,
+ precise_float: bool,
date_unit,
encoding,
- lines,
- chunksize,
+ lines: bool,
+ chunksize: Optional[int],
compression,
+ nrows: Optional[int],
):
self.orient = orient
@@ -654,11 +665,16 @@ def __init__(
self.chunksize = chunksize
self.nrows_seen = 0
self.should_close = False
+ self.nrows = nrows
if self.chunksize is not None:
self.chunksize = _validate_integer("chunksize", self.chunksize, 1)
if not self.lines:
raise ValueError("chunksize can only be passed if lines=True")
+ if self.nrows is not None:
+ self.nrows = _validate_integer("nrows", self.nrows, 0)
+ if not self.lines:
+ raise ValueError("nrows can only be passed if lines=True")
data = self._get_data_from_filepath(filepath_or_buffer)
self.data = self._preprocess_data(data)
@@ -671,9 +687,9 @@ def _preprocess_data(self, data):
If self.chunksize, we prepare the data for the `__next__` method.
Otherwise, we read it into memory for the `read` method.
"""
- if hasattr(data, "read") and not self.chunksize:
+ if hasattr(data, "read") and (not self.chunksize or not self.nrows):
data = data.read()
- if not hasattr(data, "read") and self.chunksize:
+ if not hasattr(data, "read") and (self.chunksize or self.nrows):
data = StringIO(data)
return data
@@ -721,11 +737,17 @@ def read(self):
"""
Read the whole JSON input into a pandas object.
"""
- if self.lines and self.chunksize:
- obj = concat(self)
- elif self.lines:
- data = ensure_str(self.data)
- obj = self._get_object_parser(self._combine_lines(data.split("\n")))
+ if self.lines:
+ if self.chunksize:
+ obj = concat(self)
+ elif self.nrows:
+ lines = list(islice(self.data, self.nrows))
+ lines_json = self._combine_lines(lines)
+ obj = self._get_object_parser(lines_json)
+ else:
+ data = ensure_str(self.data)
+ data = data.split("\n")
+ obj = self._get_object_parser(self._combine_lines(data))
else:
obj = self._get_object_parser(self.data)
self.close()
@@ -772,6 +794,11 @@ def close(self):
pass
def __next__(self):
+ if self.nrows:
+ if self.nrows_seen >= self.nrows:
+ self.close()
+ raise StopIteration
+
lines = list(islice(self.data, self.chunksize))
if lines:
lines_json = self._combine_lines(lines)
diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py
index e531457627342..53462eaaada8d 100644
--- a/pandas/tests/io/json/test_readlines.py
+++ b/pandas/tests/io/json/test_readlines.py
@@ -130,6 +130,7 @@ def test_readjson_chunks_closes(chunksize):
lines=True,
chunksize=chunksize,
compression=None,
+ nrows=None,
)
reader.read()
assert (
@@ -179,3 +180,42 @@ def test_readjson_unicode(monkeypatch):
result = read_json(path)
expected = pd.DataFrame({"£©µÀÆÖÞßéöÿ": ["АБВГДабвгд가"]})
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("nrows", [1, 2])
+def test_readjson_nrows(nrows):
+ # GH 33916
+ # Test reading line-format JSON to Series with nrows param
+ jsonl = """{"a": 1, "b": 2}
+ {"a": 3, "b": 4}
+ {"a": 5, "b": 6}
+ {"a": 7, "b": 8}"""
+ result = pd.read_json(jsonl, lines=True, nrows=nrows)
+ expected = pd.DataFrame({"a": [1, 3, 5, 7], "b": [2, 4, 6, 8]}).iloc[:nrows]
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("nrows,chunksize", [(2, 2), (4, 2)])
+def test_readjson_nrows_chunks(nrows, chunksize):
+ # GH 33916
+ # Test reading line-format JSON to Series with nrows and chunksize param
+ jsonl = """{"a": 1, "b": 2}
+ {"a": 3, "b": 4}
+ {"a": 5, "b": 6}
+ {"a": 7, "b": 8}"""
+ reader = read_json(jsonl, lines=True, nrows=nrows, chunksize=chunksize)
+ chunked = pd.concat(reader)
+ expected = pd.DataFrame({"a": [1, 3, 5, 7], "b": [2, 4, 6, 8]}).iloc[:nrows]
+ tm.assert_frame_equal(chunked, expected)
+
+
+def test_readjson_nrows_requires_lines():
+ # GH 33916
+ # Test ValuError raised if nrows is set without setting lines in read_json
+ jsonl = """{"a": 1, "b": 2}
+ {"a": 3, "b": 4}
+ {"a": 5, "b": 6}
+ {"a": 7, "b": 8}"""
+ msg = "nrows can only be passed if lines=True"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_json(jsonl, lines=False, nrows=2)
| - [x] closes #33916
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Add the nrows to read_json parameter that returns only the required number of json from the line delimited json | https://api.github.com/repos/pandas-dev/pandas/pulls/33962 | 2020-05-04T05:19:02Z | 2020-06-04T20:44:21Z | 2020-06-04T20:44:21Z | 2020-06-04T20:45:50Z |
PERF: 30% faster is_period_object checks | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index e3b1e1ec8cb6a..f844ad45c7026 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -75,6 +75,7 @@ from pandas._libs.tslibs.nattype cimport (
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
+from pandas._libs.tslibs.period cimport is_period_object
from pandas._libs.missing cimport (
checknull,
@@ -185,7 +186,7 @@ def is_scalar(val: object) -> bool:
# Note: PyNumber_Check check includes Decimal, Fraction, numbers.Number
return (PyNumber_Check(val)
- or util.is_period_object(val)
+ or is_period_object(val)
or is_interval(val)
or util.is_offset_object(val))
@@ -942,7 +943,7 @@ def is_period(val: object) -> bool:
-------
bool
"""
- return util.is_period_object(val)
+ return is_period_object(val)
def is_list_like(obj: object, allow_sets: bool = True) -> bool:
@@ -1417,7 +1418,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
if is_bytes_array(values, skipna=skipna):
return "bytes"
- elif util.is_period_object(val):
+ elif is_period_object(val):
if is_period_array(values):
return "period"
@@ -1849,7 +1850,7 @@ cpdef bint is_time_array(ndarray values, bint skipna=False):
cdef class PeriodValidator(TemporalValidator):
cdef inline bint is_value_typed(self, object value) except -1:
- return util.is_period_object(value)
+ return is_period_object(value)
cdef inline bint is_valid_null(self, object value) except -1:
return checknull_with_nat(value)
diff --git a/pandas/_libs/tslibs/period.pxd b/pandas/_libs/tslibs/period.pxd
new file mode 100644
index 0000000000000..eb11a4a572e85
--- /dev/null
+++ b/pandas/_libs/tslibs/period.pxd
@@ -0,0 +1 @@
+cdef bint is_period_object(object obj)
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index 5cf8fedbf0431..878dbcfd99842 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -36,7 +36,6 @@ cdef extern from "src/datetime/np_datetime.h":
npy_datetimestruct *d) nogil
cimport pandas._libs.tslibs.util as util
-from pandas._libs.tslibs.util cimport is_period_object
from pandas._libs.tslibs.timestamps import Timestamp
from pandas._libs.tslibs.timezones cimport is_utc, is_tzlocal, get_dst_info
@@ -2467,6 +2466,15 @@ class Period(_Period):
return cls._from_ordinal(ordinal, freq)
+cdef bint is_period_object(object obj):
+ """
+ Cython-optimized equivalent of isinstance(obj, Period)
+ """
+ # Note: this is significantly faster than the implementation in tslibs.util,
+ # only use the util version when necessary to prevent circular imports.
+ return isinstance(obj, _Period)
+
+
cdef int64_t _ordinal_from_fields(int year, int month, quarter, int day,
int hour, int minute, int second, freq):
base, mult = get_freq_code(freq)
| Doing an appropriate isinstance check occurs all in C-space.
```
In [1]: import pandas as pd
In [2]: from pandas._libs.lib import *
In [3]: obj = pd.Period(2004, "A")
In [4]: %timeit is_scalar(obj)
78.4 ns ± 0.761 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR
101 ns ± 1.74 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master
In [5]: %timeit is_period(obj)
54.1 ns ± 0.548 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR
80.7 ns ± 1.14 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master
In [6]: %timeit is_period([])
50.1 ns ± 1.02 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR
340 ns ± 26.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master
In [7]: %timeit is_scalar([])
65.6 ns ± 0.421 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR
67.1 ns ± 0.293 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master
In [8]: obj2 = object()
In [9]: %timeit is_scalar(obj2)
544 ns ± 6.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- PR
782 ns ± 6.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/33961 | 2020-05-04T00:03:10Z | 2020-05-04T15:29:50Z | 2020-05-04T15:29:50Z | 2020-05-04T15:33:44Z |
fix bfill, ffill and pad when calling with df.interpolate with column… | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 5c74965bffdd7..dd6ca8a0c969a 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -733,6 +733,8 @@ Missing
- 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`)
+- :meth:`DataFrame.interpolate` uses the correct axis convention now. Previously interpolating along columns lead to interpolation along indices and vice versa. Furthermore interpolating with methods ``pad``, ``ffill``, ``bfill`` and ``backfill`` are identical to using these methods with :meth:`fillna` (:issue:`12918`, :issue:`29146`)
+- Bug in :meth:`DataFrame.interpolate` when called on a DataFrame with column names of string type was throwing a ValueError. The method is no independing of the type of column names (:issue:`33956`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 85b6a8431617a..e9f7bf457cbfd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6881,30 +6881,42 @@ def interpolate(
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
+ index = self._get_axis(axis)
+
+ if isinstance(self.index, MultiIndex) and method != "linear":
+ raise ValueError(
+ "Only `method=linear` interpolation is supported on MultiIndexes."
+ )
+
+ # for the methods backfill, bfill, pad, ffill limit_direction and limit_area
+ # are being ignored, see gh-26796 for more information
+ if method in ["backfill", "bfill", "pad", "ffill"]:
+ return self.fillna(
+ method=method,
+ axis=axis,
+ inplace=inplace,
+ limit=limit,
+ downcast=downcast,
+ )
+ # Currently we need this to call the axis correctly inside the various
+ # interpolation methods
if axis == 0:
df = self
else:
df = self.T
- if isinstance(df.index, MultiIndex) and method != "linear":
- raise ValueError(
- "Only `method=linear` interpolation is supported on MultiIndexes."
- )
-
- if df.ndim == 2 and np.all(df.dtypes == np.dtype(object)):
+ if self.ndim == 2 and np.all(self.dtypes == np.dtype(object)):
raise TypeError(
"Cannot interpolate with all object-dtype columns "
"in the DataFrame. Try setting at least one "
"column to a numeric dtype."
)
- # create/use the index
if method == "linear":
# prior default
index = np.arange(len(df.index))
else:
- index = df.index
methods = {"index", "values", "nearest", "time"}
is_numeric_or_datetime = (
is_numeric_dtype(index.dtype)
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index 291a46cf03216..efb3d719016bb 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -202,7 +202,7 @@ def test_interp_leading_nans(self, check_scipy):
result = df.interpolate(method="polynomial", order=1)
tm.assert_frame_equal(result, expected)
- def test_interp_raise_on_only_mixed(self):
+ def test_interp_raise_on_only_mixed(self, axis):
df = DataFrame(
{
"A": [1, 2, np.nan, 4],
@@ -212,8 +212,13 @@ def test_interp_raise_on_only_mixed(self):
"E": [1, 2, 3, 4],
}
)
- with pytest.raises(TypeError):
- df.interpolate(axis=1)
+ msg = (
+ "Cannot interpolate with all object-dtype columns "
+ "in the DataFrame. Try setting at least one "
+ "column to a numeric dtype."
+ )
+ with pytest.raises(TypeError, match=msg):
+ df.astype("object").interpolate(axis=axis)
def test_interp_raise_on_all_object_dtype(self):
# GH 22985
@@ -272,7 +277,6 @@ def test_interp_ignore_all_good(self):
result = df[["B", "D"]].interpolate(downcast=None)
tm.assert_frame_equal(result, df[["B", "D"]])
- @pytest.mark.parametrize("axis", [0, 1])
def test_interp_time_inplace_axis(self, axis):
# GH 9687
periods = 5
@@ -296,3 +300,17 @@ def test_interp_string_axis(self, axis_name, axis_number):
result = df.interpolate(method="linear", axis=axis_name)
expected = df.interpolate(method="linear", axis=axis_number)
tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])
+ def test_interp_fillna_methods(self, axis, method):
+ # GH 12918
+ df = DataFrame(
+ {
+ "A": [1.0, 2.0, 3.0, 4.0, np.nan, 5.0],
+ "B": [2.0, 4.0, 6.0, np.nan, 8.0, 10.0],
+ "C": [3.0, 6.0, 9.0, np.nan, np.nan, 30.0],
+ }
+ )
+ expected = df.fillna(axis=axis, method=method)
+ result = df.interpolate(method=method, axis=axis)
+ tm.assert_frame_equal(result, expected)
| … dtype string (#33956)
- [x] closes #33956
- [x] closes #12918
- [x] closes #29146
- [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/33959 | 2020-05-03T23:38:37Z | 2020-06-02T22:42:51Z | 2020-06-02T22:42:50Z | 2020-06-04T11:25:02Z |
CLN: remove ABCDateOffset | diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index ceed7e29e4a35..bc479ee8f9c1f 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -21,10 +21,11 @@
from pandas._libs.interval import Interval
from pandas._libs.tslibs import NaT, Period, Timestamp, timezones
+from pandas._libs.tslibs.offsets import BaseOffset
from pandas._typing import DtypeObj, Ordered
from pandas.core.dtypes.base import ExtensionDtype
-from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCDateOffset, ABCIndexClass
+from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndexClass
from pandas.core.dtypes.inference import is_bool, is_list_like
if TYPE_CHECKING:
@@ -893,7 +894,7 @@ def __new__(cls, freq=None):
u._freq = None
return u
- if not isinstance(freq, ABCDateOffset):
+ if not isinstance(freq, BaseOffset):
freq = cls._parse_dtype_strict(freq)
try:
@@ -935,7 +936,7 @@ def construct_from_string(cls, string: str_type) -> "PeriodDtype":
if (
isinstance(string, str)
and (string.startswith("period[") or string.startswith("Period["))
- or isinstance(string, ABCDateOffset)
+ or isinstance(string, BaseOffset)
):
# do not parse string like U as period[U]
# avoid tuple to be regarded as freq
diff --git a/pandas/core/dtypes/generic.py b/pandas/core/dtypes/generic.py
index 7f98ca3d402bc..04067f9eb3fb8 100644
--- a/pandas/core/dtypes/generic.py
+++ b/pandas/core/dtypes/generic.py
@@ -63,7 +63,6 @@ def _check(cls, inst) -> bool:
"ABCTimedeltaArray", "_typ", ("timedeltaarray")
)
ABCPeriodArray = create_pandas_abc_type("ABCPeriodArray", "_typ", ("periodarray",))
-ABCDateOffset = create_pandas_abc_type("ABCDateOffset", "_typ", ("dateoffset",))
ABCExtensionArray = create_pandas_abc_type(
"ABCExtensionArray",
"_typ",
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 6c775953e18db..3ac3d4010be87 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -28,7 +28,6 @@
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
- ABCDateOffset,
ABCDatetimeIndex,
ABCPeriodIndex,
ABCSeries,
@@ -57,6 +56,8 @@
)
from pandas.core.window.numba_ import generate_numba_apply_func
+from pandas.tseries.offsets import DateOffset
+
class _Window(PandasObject, ShallowMixin, SelectionMixin):
_attributes: List[str] = [
@@ -1838,7 +1839,7 @@ def validate(self):
# we allow rolling on a datetimelike index
if (self.obj.empty or self.is_datetimelike) and isinstance(
- self.window, (str, ABCDateOffset, timedelta)
+ self.window, (str, DateOffset, timedelta)
):
self._validate_monotonic()
diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py
index f9ee943d9e6bf..8a897d026f7c5 100644
--- a/pandas/tests/dtypes/test_generic.py
+++ b/pandas/tests/dtypes/test_generic.py
@@ -38,10 +38,6 @@ def test_abc_types(self):
assert isinstance(self.sparse_array, gt.ABCSparseArray)
assert isinstance(self.categorical, gt.ABCCategorical)
- assert isinstance(pd.DateOffset(), gt.ABCDateOffset)
- assert isinstance(pd.Period("2012", freq="A-DEC").freq, gt.ABCDateOffset)
- assert not isinstance(pd.Period("2012", freq="A-DEC"), gt.ABCDateOffset)
-
assert isinstance(self.datetime_array, gt.ABCDatetimeArray)
assert not isinstance(self.datetime_index, gt.ABCDatetimeArray)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33958 | 2020-05-03T19:39:46Z | 2020-05-04T14:35:31Z | 2020-05-04T14:35:31Z | 2020-05-04T15:11:51Z | |
CLN: remove ABCSparseArray | diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index e327e11a17f4f..0877e98e55311 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -35,7 +35,7 @@
is_string_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries, ABCSparseArray
+from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna
import pandas.core.algorithms as algos
@@ -58,7 +58,7 @@
_sparray_doc_kwargs = dict(klass="SparseArray")
-def _get_fill(arr: ABCSparseArray) -> np.ndarray:
+def _get_fill(arr: "SparseArray") -> np.ndarray:
"""
Create a 0-dim ndarray containing the fill value
@@ -83,7 +83,7 @@ def _get_fill(arr: ABCSparseArray) -> np.ndarray:
def _sparse_array_op(
- left: ABCSparseArray, right: ABCSparseArray, op: Callable, name: str
+ left: "SparseArray", right: "SparseArray", op: Callable, name: str
) -> Any:
"""
Perform a binary operation between two arrays.
diff --git a/pandas/core/dtypes/generic.py b/pandas/core/dtypes/generic.py
index 7f98ca3d402bc..ea6ce2618c7ff 100644
--- a/pandas/core/dtypes/generic.py
+++ b/pandas/core/dtypes/generic.py
@@ -56,7 +56,6 @@ def _check(cls, inst) -> bool:
ABCSeries = create_pandas_abc_type("ABCSeries", "_typ", ("series",))
ABCDataFrame = create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe",))
-ABCSparseArray = create_pandas_abc_type("ABCSparseArray", "_subtyp", ("sparse_array",))
ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ", ("categorical"))
ABCDatetimeArray = create_pandas_abc_type("ABCDatetimeArray", "_typ", ("datetimearray"))
ABCTimedeltaArray = create_pandas_abc_type(
diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py
index 7c63bc43de67e..63086f62b6445 100644
--- a/pandas/core/ops/methods.py
+++ b/pandas/core/ops/methods.py
@@ -3,7 +3,7 @@
"""
import operator
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries, ABCSparseArray
+from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.ops.roperator import (
radd,
@@ -225,10 +225,4 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special):
def _add_methods(cls, new_methods):
for name, method in new_methods.items():
- # For most methods, if we find that the class already has a method
- # of the same name, it is OK to over-write it. The exception is
- # inplace methods (__iadd__, __isub__, ...) for SparseArray, which
- # retain the np.ndarray versions.
- force = not (issubclass(cls, ABCSparseArray) and name.startswith("__i"))
- if force or name not in cls.__dict__:
- setattr(cls, name, method)
+ setattr(cls, name, method)
diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py
index f9ee943d9e6bf..8023b4e2c19d9 100644
--- a/pandas/tests/dtypes/test_generic.py
+++ b/pandas/tests/dtypes/test_generic.py
@@ -35,7 +35,7 @@ def test_abc_types(self):
assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCIndexClass)
assert isinstance(pd.Series([1, 2, 3]), gt.ABCSeries)
assert isinstance(self.df, gt.ABCDataFrame)
- assert isinstance(self.sparse_array, gt.ABCSparseArray)
+ assert isinstance(self.sparse_array, gt.ABCExtensionArray)
assert isinstance(self.categorical, gt.ABCCategorical)
assert isinstance(pd.DateOffset(), gt.ABCDateOffset)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33957 | 2020-05-03T19:01:16Z | 2020-05-04T14:36:23Z | 2020-05-04T14:36:23Z | 2020-05-04T15:15:08Z | |
DOC: update conf.py to use new numpy doc url | diff --git a/doc/source/conf.py b/doc/source/conf.py
index d2404b757ca11..ee0d4ca3f2a24 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -410,7 +410,7 @@
intersphinx_mapping = {
"dateutil": ("https://dateutil.readthedocs.io/en/latest/", None),
"matplotlib": ("https://matplotlib.org/", None),
- "numpy": ("https://docs.scipy.org/doc/numpy/", None),
+ "numpy": ("https://numpy.org/doc/stable/", None),
"pandas-gbq": ("https://pandas-gbq.readthedocs.io/en/latest/", None),
"py": ("https://pylib.readthedocs.io/en/latest/", None),
"python": ("https://docs.python.org/3/", None),
| - [X] closes #33953
- [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/33954 | 2020-05-03T13:50:10Z | 2020-05-05T09:06:18Z | 2020-05-05T09:06:18Z | 2020-05-05T11:30:45Z |
BUG: CategoricalIndex.__contains__ incorrect NaTs | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 0c9db271edf37..9cdb5dfc47776 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -37,7 +37,7 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.inference import is_hashable
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
from pandas.core import ops
from pandas.core.accessor import PandasDelegate, delegate_names
@@ -1834,7 +1834,7 @@ def __contains__(self, key) -> bool:
Returns True if `key` is in this Categorical.
"""
# if key is a NaN, check if any NaN is in self.
- if is_scalar(key) and isna(key):
+ if is_valid_nat_for_dtype(key, self.categories.dtype):
return self.isna().any()
return contains(self, key, container=self._codes)
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 0cf6698d316bb..80d3e5c8a0dbe 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -19,7 +19,7 @@
is_scalar,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas.core.dtypes.missing import isna
+from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
from pandas.core import accessor
from pandas.core.algorithms import take_1d
@@ -365,10 +365,9 @@ def _has_complex_internals(self) -> bool:
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
- if is_scalar(key) and isna(key):
+ if is_valid_nat_for_dtype(key, self.categories.dtype):
return self.hasnans
- hash(key)
return contains(self, key, container=self._engine)
@doc(Index.astype)
diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py
index a36568bbbe633..9cf901c0797d8 100644
--- a/pandas/tests/indexes/categorical/test_indexing.py
+++ b/pandas/tests/indexes/categorical/test_indexing.py
@@ -285,6 +285,43 @@ def test_contains_nan(self):
ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef"))
assert np.nan in ci
+ @pytest.mark.parametrize("unwrap", [True, False])
+ def test_contains_na_dtype(self, unwrap):
+ dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT)
+ pi = dti.to_period("D")
+ tdi = dti - dti[-1]
+ ci = CategoricalIndex(dti)
+
+ obj = ci
+ if unwrap:
+ obj = ci._data
+
+ assert np.nan in obj
+ assert None in obj
+ assert pd.NaT in obj
+ assert np.datetime64("NaT") in obj
+ assert np.timedelta64("NaT") not in obj
+
+ obj2 = CategoricalIndex(tdi)
+ if unwrap:
+ obj2 = obj2._data
+
+ assert np.nan in obj2
+ assert None in obj2
+ assert pd.NaT in obj2
+ assert np.datetime64("NaT") not in obj2
+ assert np.timedelta64("NaT") in obj2
+
+ obj3 = CategoricalIndex(pi)
+ if unwrap:
+ obj3 = obj3._data
+
+ assert np.nan in obj3
+ assert None in obj3
+ assert pd.NaT in obj3
+ assert np.datetime64("NaT") not in obj3
+ assert np.timedelta64("NaT") not in obj3
+
@pytest.mark.parametrize(
"item, expected",
[
| - [ ] 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/33947 | 2020-05-02T20:35:34Z | 2020-05-05T17:17:55Z | 2020-05-05T17:17:55Z | 2020-05-05T17:19:15Z |
PERF: use fastpath for is_categorical_dtype calls | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 74c4c661b4b83..8fbdcb89dafca 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -718,7 +718,7 @@ def _get_ilevel_values(index, level):
assert_interval_array_equal(left._values, right._values)
if check_categorical:
- if is_categorical_dtype(left) or is_categorical_dtype(right):
+ if is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype):
assert_categorical_equal(left._values, right._values, obj=f"{obj} category")
@@ -1250,7 +1250,7 @@ def assert_series_equal(
assert_attr_equal("name", left, right, obj=obj)
if check_categorical:
- if is_categorical_dtype(left) or is_categorical_dtype(right):
+ if is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype):
assert_categorical_equal(
left._values,
right._values,
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 7ea2ff95ea0de..309b6e0ad5e1a 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1123,7 +1123,7 @@ def _map_values(self, mapper, na_action=None):
if isinstance(mapper, ABCSeries):
# Since values were input this means we came from either
# a dict or a series and mapper should be an index
- if is_categorical_dtype(self._values):
+ if is_categorical_dtype(self.dtype):
# use the built in categorical series mapper which saves
# time by mapping the categories instead of all values
return self._values.map(mapper)
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index d67811988d0f8..71d7a07aadf7f 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -458,7 +458,7 @@ def _cython_operation(
# categoricals are only 1d, so we
# are not setup for dim transforming
- if is_categorical_dtype(values) or is_sparse(values):
+ if is_categorical_dtype(values.dtype) or is_sparse(values.dtype):
raise NotImplementedError(f"{values.dtype} dtype not supported")
elif is_datetime64_any_dtype(values):
if how in ["add", "prod", "cumsum", "cumprod"]:
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index db2264db438f4..598d228723ac8 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -434,7 +434,7 @@ def __new__(cls, data: "Series"):
f"cannot convert an object of type {type(data)} to a datetimelike index"
)
- orig = data if is_categorical_dtype(data) else None
+ orig = data if is_categorical_dtype(data.dtype) else None
if orig is not None:
data = data._constructor(
orig.array,
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 79af28dc5f2ce..cf17ce9db6b1a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -631,6 +631,9 @@ def astype(self, dtype, copy=True):
Index
Index with values cast to specified dtype.
"""
+ if dtype is not None:
+ dtype = pandas_dtype(dtype)
+
if is_dtype_equal(self.dtype, dtype):
return self.copy() if copy else self
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 86110433b36b1..72369a13b150f 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -651,7 +651,7 @@ def values(self):
for i in range(self.nlevels):
vals = self._get_level_values(i)
- if is_categorical_dtype(vals):
+ if is_categorical_dtype(vals.dtype):
vals = vals._internal_get_values()
if isinstance(vals.dtype, ExtensionDtype) or isinstance(
vals, (ABCDatetimeIndex, ABCTimedeltaIndex)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 39df7ae3c9b60..d028d840448ea 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -535,10 +535,13 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
)
raise TypeError(msg)
+ if dtype is not None:
+ dtype = pandas_dtype(dtype)
+
# may need to convert to categorical
if is_categorical_dtype(dtype):
- if is_categorical_dtype(self.values):
+ if is_categorical_dtype(self.values.dtype):
# GH 10696/18593: update an existing categorical efficiently
return self.make_block(self.values.astype(dtype, copy=copy))
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 76b851d8ac923..72d778524a364 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -2092,7 +2092,7 @@ class StringMethods(NoNewAttributesMixin):
def __init__(self, data):
self._inferred_dtype = self._validate(data)
- self._is_categorical = is_categorical_dtype(data)
+ self._is_categorical = is_categorical_dtype(data.dtype)
self._is_string = data.dtype.name == "string"
# ._values.categories works for both Series/Index
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 5845202550326..82380d456cd6d 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2213,19 +2213,20 @@ def take_data(self):
return self.data
@classmethod
- def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
+ def _get_atom(cls, values: ArrayLike) -> "Col":
"""
Get an appropriately typed and shaped pytables.Col object for values.
"""
dtype = values.dtype
- itemsize = dtype.itemsize
+ itemsize = dtype.itemsize # type: ignore
shape = values.shape
if values.ndim == 1:
# EA, use block shape pretending it is 2D
+ # TODO(EA2D): not necessary with 2D EAs
shape = (1, values.size)
- if is_categorical_dtype(dtype):
+ if isinstance(values, Categorical):
codes = values.codes
atom = cls.get_atom_data(shape, kind=codes.dtype.name)
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
@@ -2887,7 +2888,7 @@ def write_array(self, key: str, value: ArrayLike, items: Optional[Index] = None)
empty_array = value.size == 0
transposed = False
- if is_categorical_dtype(value):
+ if is_categorical_dtype(value.dtype):
raise NotImplementedError(
"Cannot store a category dtype in a HDF5 dataset that uses format="
'"fixed". Use format="table".'
@@ -3795,7 +3796,7 @@ def get_blk_items(mgr, blocks):
tz = _get_tz(data_converted.tz) if hasattr(data_converted, "tz") else None
meta = metadata = ordered = None
- if is_categorical_dtype(data_converted):
+ if is_categorical_dtype(data_converted.dtype):
ordered = data_converted.ordered
meta = "category"
metadata = np.array(data_converted.categories, copy=False).ravel()
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index b9b43685415d1..f445f05c2ee05 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -2132,7 +2132,7 @@ def _prepare_categoricals(self, data: DataFrame) -> DataFrame:
Check for categorical columns, retain categorical information for
Stata file and convert categorical data to int
"""
- is_cat = [is_categorical_dtype(data[col]) for col in data]
+ is_cat = [is_categorical_dtype(data[col].dtype) for col in data]
self._is_col_cat = is_cat
self._value_labels: List[StataValueLabel] = []
if not any(is_cat):
diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py
index 6bab60f05ce89..72417d3afd579 100644
--- a/pandas/tests/base/test_misc.py
+++ b/pandas/tests/base/test_misc.py
@@ -122,8 +122,8 @@ def test_memory_usage(index_or_series_obj):
is_object = is_object_dtype(obj) or (
isinstance(obj, Series) and is_object_dtype(obj.index)
)
- is_categorical = is_categorical_dtype(obj) or (
- isinstance(obj, Series) and is_categorical_dtype(obj.index)
+ is_categorical = is_categorical_dtype(obj.dtype) or (
+ isinstance(obj, Series) and is_categorical_dtype(obj.index.dtype)
)
if len(obj) == 0:
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py
index cd23cd6aa9c63..486855f5c37cd 100644
--- a/pandas/tests/frame/test_alter_axes.py
+++ b/pandas/tests/frame/test_alter_axes.py
@@ -234,9 +234,9 @@ def test_setitem(self):
df["D"] = s.values
df["E"] = np.array(s.values)
- assert is_categorical_dtype(df["B"])
+ assert is_categorical_dtype(df["B"].dtype)
assert is_interval_dtype(df["B"].cat.categories)
- assert is_categorical_dtype(df["D"])
+ assert is_categorical_dtype(df["D"].dtype)
assert is_interval_dtype(df["D"].cat.categories)
assert is_object_dtype(df["C"])
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index c9634c4c90809..98edb56260b01 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -156,7 +156,7 @@ def test_slicing_and_getting_ops(self):
# frame
res_df = df.iloc[2:4, :]
tm.assert_frame_equal(res_df, exp_df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
# row
res_row = df.iloc[2, :]
@@ -166,7 +166,7 @@ def test_slicing_and_getting_ops(self):
# col
res_col = df.iloc[:, 0]
tm.assert_series_equal(res_col, exp_col)
- assert is_categorical_dtype(res_col)
+ assert is_categorical_dtype(res_col.dtype)
# single value
res_val = df.iloc[2, 0]
@@ -176,7 +176,7 @@ def test_slicing_and_getting_ops(self):
# frame
res_df = df.loc["j":"k", :]
tm.assert_frame_equal(res_df, exp_df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
# row
res_row = df.loc["j", :]
@@ -186,7 +186,7 @@ def test_slicing_and_getting_ops(self):
# col
res_col = df.loc[:, "cats"]
tm.assert_series_equal(res_col, exp_col)
- assert is_categorical_dtype(res_col)
+ assert is_categorical_dtype(res_col.dtype)
# single value
res_val = df.loc["j", "cats"]
@@ -197,7 +197,7 @@ def test_slicing_and_getting_ops(self):
# res_df = df.loc["j":"k",[0,1]] # doesn't work?
res_df = df.loc["j":"k", :]
tm.assert_frame_equal(res_df, exp_df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
# row
res_row = df.loc["j", :]
@@ -207,7 +207,7 @@ def test_slicing_and_getting_ops(self):
# col
res_col = df.loc[:, "cats"]
tm.assert_series_equal(res_col, exp_col)
- assert is_categorical_dtype(res_col)
+ assert is_categorical_dtype(res_col.dtype)
# single value
res_val = df.loc["j", df.columns[0]]
@@ -240,23 +240,23 @@ def test_slicing_and_getting_ops(self):
res_df = df.iloc[slice(2, 4)]
tm.assert_frame_equal(res_df, exp_df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
res_df = df.iloc[[2, 3]]
tm.assert_frame_equal(res_df, exp_df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
res_col = df.iloc[:, 0]
tm.assert_series_equal(res_col, exp_col)
- assert is_categorical_dtype(res_col)
+ assert is_categorical_dtype(res_col.dtype)
res_df = df.iloc[:, slice(0, 2)]
tm.assert_frame_equal(res_df, df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
res_df = df.iloc[:, [0, 1]]
tm.assert_frame_equal(res_df, df)
- assert is_categorical_dtype(res_df["cats"])
+ assert is_categorical_dtype(res_df["cats"].dtype)
def test_slicing_doc_examples(self):
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index eaa92fa53d799..6839e3ed0bbea 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -1065,7 +1065,7 @@ def test_categorical_order(self, file):
# Check identity of codes
for col in expected:
- if is_categorical_dtype(expected[col]):
+ if is_categorical_dtype(expected[col].dtype):
tm.assert_series_equal(expected[col].cat.codes, parsed[col].cat.codes)
tm.assert_index_equal(
expected[col].cat.categories, parsed[col].cat.categories
@@ -1095,7 +1095,7 @@ def test_categorical_ordering(self, file):
parsed_unordered = read_stata(file, order_categoricals=False)
for col in parsed:
- if not is_categorical_dtype(parsed[col]):
+ if not is_categorical_dtype(parsed[col].dtype):
continue
assert parsed[col].cat.ordered
assert not parsed_unordered[col].cat.ordered
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index a92e628960456..4408aa0bbce4a 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1729,7 +1729,7 @@ def test_dtype_on_merged_different(self, change, join_type, left, right):
X = change(right.X.astype("object"))
right = right.assign(X=X)
- assert is_categorical_dtype(left.X.values)
+ assert is_categorical_dtype(left.X.values.dtype)
# assert not left.X.values.is_dtype_equal(right.X.values)
merged = pd.merge(left, right, on="X", how=join_type)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 85f47d0f6f5a4..d78324d92a036 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -377,12 +377,12 @@ def test_constructor_categorical_dtype(self):
result = pd.Series(
["a", "b"], dtype=CategoricalDtype(["a", "b", "c"], ordered=True)
)
- assert is_categorical_dtype(result) is True
+ assert is_categorical_dtype(result.dtype) is True
tm.assert_index_equal(result.cat.categories, pd.Index(["a", "b", "c"]))
assert result.cat.ordered
result = pd.Series(["a", "b"], dtype=CategoricalDtype(["b", "a"]))
- assert is_categorical_dtype(result)
+ assert is_categorical_dtype(result.dtype)
tm.assert_index_equal(result.cat.categories, pd.Index(["b", "a"]))
assert result.cat.ordered is False
| This doesn't get all of them | https://api.github.com/repos/pandas-dev/pandas/pulls/33945 | 2020-05-02T18:48:49Z | 2020-05-04T16:55:31Z | 2020-05-04T16:55:31Z | 2020-05-04T17:01:58Z |
TYP: annotate core.algorithms | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 449d9ad8301e4..cc0fdae094cf9 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -11,7 +11,7 @@
from pandas._libs import Timestamp, algos, hashtable as htable, lib
from pandas._libs.tslib import iNaT
-from pandas._typing import AnyArrayLike, DtypeObj
+from pandas._typing import AnyArrayLike, ArrayLike, DtypeObj
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import (
@@ -44,6 +44,7 @@
is_timedelta64_dtype,
is_unsigned_integer_dtype,
needs_i8_conversion,
+ pandas_dtype,
)
from pandas.core.dtypes.generic import (
ABCExtensionArray,
@@ -66,7 +67,9 @@
# --------------- #
# dtype access #
# --------------- #
-def _ensure_data(values, dtype=None):
+def _ensure_data(
+ values, dtype: Optional[DtypeObj] = None
+) -> Tuple[np.ndarray, DtypeObj]:
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
@@ -88,29 +91,30 @@ def _ensure_data(values, dtype=None):
Returns
-------
values : ndarray
- pandas_dtype : str or dtype
+ pandas_dtype : np.dtype or ExtensionDtype
"""
+
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"
+ return ensure_object(np.asarray(values)), np.dtype("object")
elif is_object_dtype(values) and dtype is None:
- return ensure_object(np.asarray(values)), "object"
+ return ensure_object(np.asarray(values)), np.dtype("object")
try:
if is_bool_dtype(values) or is_bool_dtype(dtype):
# we are actually coercing to uint64
# until our algos support uint8 directly (see TODO)
- return np.asarray(values).astype("uint64"), "bool"
+ return np.asarray(values).astype("uint64"), np.dtype("bool")
elif is_signed_integer_dtype(values) or is_signed_integer_dtype(dtype):
- return ensure_int64(values), "int64"
+ return ensure_int64(values), np.dtype("int64")
elif is_unsigned_integer_dtype(values) or is_unsigned_integer_dtype(dtype):
- return ensure_uint64(values), "uint64"
+ return ensure_uint64(values), np.dtype("uint64")
elif is_float_dtype(values) or is_float_dtype(dtype):
- return ensure_float64(values), "float64"
+ return ensure_float64(values), np.dtype("float64")
elif is_complex_dtype(values) or is_complex_dtype(dtype):
# ignore the fact that we are casting to float
@@ -118,12 +122,12 @@ def _ensure_data(values, dtype=None):
with catch_warnings():
simplefilter("ignore", np.ComplexWarning)
values = ensure_float64(values)
- return values, "float64"
+ return values, np.dtype("float64")
except (TypeError, ValueError, OverflowError):
# if we are trying to coerce to a dtype
# and it is incompat this will fall through to here
- return ensure_object(values), "object"
+ return ensure_object(values), np.dtype("object")
# datetimelike
vals_dtype = getattr(values, "dtype", None)
@@ -159,7 +163,7 @@ def _ensure_data(values, dtype=None):
is_categorical_dtype(dtype) or dtype is None
):
values = values.codes
- dtype = "category"
+ dtype = pandas_dtype("category")
# we are actually coercing to int64
# until our algos support int* directly (not all do)
@@ -169,22 +173,24 @@ def _ensure_data(values, dtype=None):
# we have failed, return object
values = np.asarray(values, dtype=np.object)
- return ensure_object(values), "object"
+ return ensure_object(values), np.dtype("object")
-def _reconstruct_data(values, dtype, original):
+def _reconstruct_data(
+ values: ArrayLike, dtype: DtypeObj, original: AnyArrayLike
+) -> ArrayLike:
"""
reverse of _ensure_data
Parameters
----------
- values : ndarray
- dtype : pandas_dtype
- original : ndarray-like
+ values : np.ndarray or ExtensionArray
+ dtype : np.ndtype or ExtensionDtype
+ original : AnyArrayLike
Returns
-------
- Index for extension types, otherwise ndarray casted to dtype
+ ExtensionArray or np.ndarray
"""
if is_extension_array_dtype(dtype):
values = dtype.construct_array_type()._from_sequence(values)
@@ -416,6 +422,7 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray:
if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)):
values = construct_1d_object_array_from_listlike(list(values))
+ # TODO: could use ensure_arraylike here
comps = extract_array(comps, extract_numpy=True)
if is_categorical_dtype(comps):
@@ -729,6 +736,7 @@ def value_counts(
return result
+# Called once from SparseArray
def _value_counts_arraylike(values, dropna: bool):
"""
Parameters
@@ -823,6 +831,7 @@ def mode(values, dropna: bool = True) -> "Series":
# categorical is a fast-path
if is_categorical_dtype(values):
if isinstance(values, Series):
+ # TODO: should we be passing `name` below?
return Series(values._values.mode(dropna=dropna), name=values.name)
return values.mode(dropna=dropna)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33944 | 2020-05-02T16:51:44Z | 2020-05-06T18:17:23Z | 2020-05-06T18:17:23Z | 2020-05-06T19:01:06Z | |
TST/REF: Fixturize constant functions in ConsistencyBase | diff --git a/pandas/tests/window/common.py b/pandas/tests/window/common.py
index 7a7ab57cdb904..25989191ae657 100644
--- a/pandas/tests/window/common.py
+++ b/pandas/tests/window/common.py
@@ -25,40 +25,6 @@ def _create_data(self):
class ConsistencyBase(Base):
- base_functions = [
- (lambda v: Series(v).count(), None, "count"),
- (lambda v: Series(v).max(), None, "max"),
- (lambda v: Series(v).min(), None, "min"),
- (lambda v: Series(v).sum(), None, "sum"),
- (lambda v: Series(v).mean(), None, "mean"),
- (lambda v: Series(v).std(), 1, "std"),
- (lambda v: Series(v).cov(Series(v)), None, "cov"),
- (lambda v: Series(v).corr(Series(v)), None, "corr"),
- (lambda v: Series(v).var(), 1, "var"),
- # restore once GH 8086 is fixed
- # lambda v: Series(v).skew(), 3, 'skew'),
- # (lambda v: Series(v).kurt(), 4, 'kurt'),
- # restore once GH 8084 is fixed
- # lambda v: Series(v).quantile(0.3), None, 'quantile'),
- (lambda v: Series(v).median(), None, "median"),
- (np.nanmax, 1, "max"),
- (np.nanmin, 1, "min"),
- (np.nansum, 1, "sum"),
- (np.nanmean, 1, "mean"),
- (lambda v: np.nanstd(v, ddof=1), 1, "std"),
- (lambda v: np.nanvar(v, ddof=1), 1, "var"),
- (np.nanmedian, 1, "median"),
- ]
- no_nan_functions = [
- (np.max, None, "max"),
- (np.min, None, "min"),
- (np.sum, None, "sum"),
- (np.mean, None, "mean"),
- (lambda v: np.std(v, ddof=1), 1, "std"),
- (lambda v: np.var(v, ddof=1), 1, "var"),
- (np.median, None, "median"),
- ]
-
def _create_data(self):
super()._create_data()
diff --git a/pandas/tests/window/moments/conftest.py b/pandas/tests/window/moments/conftest.py
index 2002f4d0bff43..39e6ae71162a9 100644
--- a/pandas/tests/window/moments/conftest.py
+++ b/pandas/tests/window/moments/conftest.py
@@ -18,3 +18,61 @@ def binary_ew_data():
@pytest.fixture(params=[0, 1, 2])
def min_periods(request):
return request.param
+
+
+base_functions_list = [
+ (lambda v: Series(v).count(), None, "count"),
+ (lambda v: Series(v).max(), None, "max"),
+ (lambda v: Series(v).min(), None, "min"),
+ (lambda v: Series(v).sum(), None, "sum"),
+ (lambda v: Series(v).mean(), None, "mean"),
+ (lambda v: Series(v).std(), 1, "std"),
+ (lambda v: Series(v).cov(Series(v)), None, "cov"),
+ (lambda v: Series(v).corr(Series(v)), None, "corr"),
+ (lambda v: Series(v).var(), 1, "var"),
+ # restore once GH 8086 is fixed
+ # lambda v: Series(v).skew(), 3, 'skew'),
+ # (lambda v: Series(v).kurt(), 4, 'kurt'),
+ # restore once GH 8084 is fixed
+ # lambda v: Series(v).quantile(0.3), None, 'quantile'),
+ (lambda v: Series(v).median(), None, "median"),
+ (np.nanmax, 1, "max"),
+ (np.nanmin, 1, "min"),
+ (np.nansum, 1, "sum"),
+ (np.nanmean, 1, "mean"),
+ (lambda v: np.nanstd(v, ddof=1), 1, "std"),
+ (lambda v: np.nanvar(v, ddof=1), 1, "var"),
+ (np.nanmedian, 1, "median"),
+]
+
+no_nan_functions_list = [
+ (np.max, None, "max"),
+ (np.min, None, "min"),
+ (np.sum, None, "sum"),
+ (np.mean, None, "mean"),
+ (lambda v: np.std(v, ddof=1), 1, "std"),
+ (lambda v: np.var(v, ddof=1), 1, "var"),
+ (np.median, None, "median"),
+]
+
+
+@pytest.fixture(scope="session")
+def base_functions():
+ """Fixture for base functions.
+
+ Returns
+ -------
+ List of tuples: (applied function, require_min_periods, name of applied function)
+ """
+ return base_functions_list
+
+
+@pytest.fixture(scope="session")
+def no_nan_functions():
+ """Fixture for no nan functions.
+
+ Returns
+ -------
+ List of tuples: (applied function, require_min_periods, name of applied function)
+ """
+ return no_nan_functions_list
diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py
index d20ab5131cf17..6aff5b78b4ada 100644
--- a/pandas/tests/window/moments/test_moments_expanding.py
+++ b/pandas/tests/window/moments/test_moments_expanding.py
@@ -145,50 +145,52 @@ def _check_expanding_has_min_periods(self, func, static_comp, has_min_periods):
result = func(ser)
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_apply_consistency(self, consistency_data, min_periods):
- x, is_constant, no_nans = consistency_data
- with warnings.catch_warnings():
- warnings.filterwarnings(
- "ignore",
- message=".*(empty slice|0 for slice).*",
- category=RuntimeWarning,
- )
- # test consistency between expanding_xyz() and either (a)
- # expanding_apply of Series.xyz(), or (b) expanding_apply of
- # np.nanxyz()
- functions = self.base_functions
-
- # GH 8269
- if no_nans:
- functions = self.base_functions + self.no_nan_functions
- for (f, require_min_periods, name) in functions:
- expanding_f = getattr(x.expanding(min_periods=min_periods), name)
-
- if (
- require_min_periods
- and (min_periods is not None)
- and (min_periods < require_min_periods)
- ):
- continue
-
- if name == "count":
- expanding_f_result = expanding_f()
- expanding_apply_f_result = x.expanding(min_periods=0).apply(
- func=f, raw=True
- )
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_expanding_apply_consistency(
+ consistency_data, base_functions, no_nan_functions, min_periods
+):
+ x, is_constant, no_nans = consistency_data
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
+ )
+ # test consistency between expanding_xyz() and either (a)
+ # expanding_apply of Series.xyz(), or (b) expanding_apply of
+ # np.nanxyz()
+ functions = base_functions
+
+ # GH 8269
+ if no_nans:
+ functions = base_functions + no_nan_functions
+ for (f, require_min_periods, name) in functions:
+ expanding_f = getattr(x.expanding(min_periods=min_periods), name)
+
+ if (
+ require_min_periods
+ and (min_periods is not None)
+ and (min_periods < require_min_periods)
+ ):
+ continue
+
+ if name == "count":
+ expanding_f_result = expanding_f()
+ expanding_apply_f_result = x.expanding(min_periods=0).apply(
+ func=f, raw=True
+ )
+ else:
+ if name in ["cov", "corr"]:
+ expanding_f_result = expanding_f(pairwise=False)
else:
- if name in ["cov", "corr"]:
- expanding_f_result = expanding_f(pairwise=False)
- else:
- expanding_f_result = expanding_f()
- expanding_apply_f_result = x.expanding(
- min_periods=min_periods
- ).apply(func=f, raw=True)
-
- # GH 9422
- if name in ["sum", "prod"]:
- tm.assert_equal(expanding_f_result, expanding_apply_f_result)
+ expanding_f_result = expanding_f()
+ expanding_apply_f_result = x.expanding(min_periods=min_periods).apply(
+ func=f, raw=True
+ )
+
+ # GH 9422
+ if name in ["sum", "prod"]:
+ tm.assert_equal(expanding_f_result, expanding_apply_f_result)
@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index c7d3a50ec13ae..28ad2b8663efe 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -946,58 +946,6 @@ class TestRollingMomentsConsistency(ConsistencyBase):
def setup_method(self, method):
self._create_data()
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_apply_consistency(
- self, consistency_data, window, min_periods, center
- ):
- x, is_constant, no_nans = consistency_data
- with warnings.catch_warnings():
- warnings.filterwarnings(
- "ignore",
- message=".*(empty slice|0 for slice).*",
- category=RuntimeWarning,
- )
- # test consistency between rolling_xyz() and either (a)
- # rolling_apply of Series.xyz(), or (b) rolling_apply of
- # np.nanxyz()
- functions = self.base_functions
-
- # GH 8269
- if no_nans:
- functions = self.base_functions + self.no_nan_functions
- for (f, require_min_periods, name) in functions:
- rolling_f = getattr(
- x.rolling(window=window, center=center, min_periods=min_periods),
- name,
- )
-
- if (
- require_min_periods
- and (min_periods is not None)
- and (min_periods < require_min_periods)
- ):
- continue
-
- if name == "count":
- rolling_f_result = rolling_f()
- rolling_apply_f_result = x.rolling(
- window=window, min_periods=min_periods, center=center
- ).apply(func=f, raw=True)
- else:
- if name in ["cov", "corr"]:
- rolling_f_result = rolling_f(pairwise=False)
- else:
- rolling_f_result = rolling_f()
- rolling_apply_f_result = x.rolling(
- window=window, min_periods=min_periods, center=center
- ).apply(func=f, raw=True)
-
- # GH 9422
- if name in ["sum", "prod"]:
- tm.assert_equal(rolling_f_result, rolling_apply_f_result)
-
# binary moments
def test_rolling_cov(self):
A = self.series
@@ -1052,6 +1000,58 @@ def test_flex_binary_frame(self, method):
tm.assert_frame_equal(res3, exp)
+@pytest.mark.slow
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_apply_consistency(
+ consistency_data, base_functions, no_nan_functions, window, min_periods, center
+):
+ x, is_constant, no_nans = consistency_data
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
+ )
+ # test consistency between rolling_xyz() and either (a)
+ # rolling_apply of Series.xyz(), or (b) rolling_apply of
+ # np.nanxyz()
+ functions = base_functions
+
+ # GH 8269
+ if no_nans:
+ functions = no_nan_functions + base_functions
+ for (f, require_min_periods, name) in functions:
+ rolling_f = getattr(
+ x.rolling(window=window, center=center, min_periods=min_periods), name,
+ )
+
+ if (
+ require_min_periods
+ and (min_periods is not None)
+ and (min_periods < require_min_periods)
+ ):
+ continue
+
+ if name == "count":
+ rolling_f_result = rolling_f()
+ rolling_apply_f_result = x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).apply(func=f, raw=True)
+ else:
+ if name in ["cov", "corr"]:
+ rolling_f_result = rolling_f(pairwise=False)
+ else:
+ rolling_f_result = rolling_f()
+ rolling_apply_f_result = x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).apply(func=f, raw=True)
+
+ # GH 9422
+ if name in ["sum", "prod"]:
+ tm.assert_equal(rolling_f_result, rolling_apply_f_result)
+
+
@pytest.mark.parametrize("window", range(7))
def test_rolling_corr_with_zero_variance(window):
# GH 18430
@@ -1431,6 +1431,7 @@ def test_moment_functions_zero_length_pairwise():
tm.assert_frame_equal(df2_result, df2_expected)
+@pytest.mark.slow
@pytest.mark.parametrize(
"window,min_periods,center", list(_rolling_consistency_cases())
)
@@ -1455,6 +1456,7 @@ def test_rolling_consistency_var(consistency_data, window, min_periods, center):
)
+@pytest.mark.slow
@pytest.mark.parametrize(
"window,min_periods,center", list(_rolling_consistency_cases())
)
@@ -1477,6 +1479,7 @@ def test_rolling_consistency_std(consistency_data, window, min_periods, center):
)
+@pytest.mark.slow
@pytest.mark.parametrize(
"window,min_periods,center", list(_rolling_consistency_cases())
)
| This PR fixturizes the last constants (`base_functions` and `no_nan_functions`) in ConsistencyBase, and take corresponding tests out of class.
After this one, only constants in `Base` class needs to be fixed (if `Base` is also wanted to be cleaned)
cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/33943 | 2020-05-02T16:41:45Z | 2020-05-10T15:45:53Z | 2020-05-10T15:45:53Z | 2020-05-10T15:45:59Z |
TST: add pattern for nearest | diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index f15d39e9e6456..4be48a4d060a8 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -535,11 +535,14 @@ def test_upsample_with_limit():
tm.assert_series_equal(result, expected)
-def test_nearest_upsample_with_limit():
- rng = date_range("1/1/2000", periods=3, freq="5t")
+@pytest.mark.parametrize("freq", ["Y", "10M", "5D", "10H", "5Min", "10S"])
+@pytest.mark.parametrize("rule", ["Y", "3M", "15D", "30H", "15Min", "30S"])
+def test_nearest_upsample_with_limit(tz_aware_fixture, freq, rule):
+ # GH 33939
+ rng = date_range("1/1/2000", periods=3, freq=freq, tz=tz_aware_fixture)
ts = Series(np.random.randn(len(rng)), rng)
- result = ts.resample("t").nearest(limit=2)
+ result = ts.resample(rule).nearest(limit=2)
expected = ts.reindex(result.index, method="nearest", limit=2)
tm.assert_series_equal(result, expected)
| - [ ] closes #33895
- [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/33939 | 2020-05-02T08:26:10Z | 2020-05-06T17:58:20Z | 2020-05-06T17:58:20Z | 2020-05-06T17:58:24Z |
TST: raise InvalidIndexError with IntervalIndex.get_value and get_loc | diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py
index 0e08a3f41b666..718136fca6c80 100644
--- a/pandas/tests/indexes/interval/test_indexing.py
+++ b/pandas/tests/indexes/interval/test_indexing.py
@@ -158,6 +158,15 @@ def test_get_loc_decreasing(self, values):
expected = 0
assert result == expected
+ @pytest.mark.parametrize("key", [[5], (2, 3)])
+ def test_get_loc_non_scalar_errors(self, key):
+ # GH 31117
+ idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
+
+ msg = str(key)
+ with pytest.raises(InvalidIndexError, match=msg):
+ idx.get_loc(key)
+
class TestGetIndexer:
@pytest.mark.parametrize(
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 1b2bfa8573c21..3f29e6ce0beb6 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -19,6 +19,7 @@
)
import pandas._testing as tm
import pandas.core.common as com
+from pandas.core.indexes.base import InvalidIndexError
@pytest.fixture(scope="class", params=[None, "foo"])
@@ -857,6 +858,17 @@ def test_is_all_dates(self):
year_2017_index = pd.IntervalIndex([year_2017])
assert not year_2017_index.is_all_dates
+ @pytest.mark.parametrize("key", [[5], (2, 3)])
+ def test_get_value_non_scalar_errors(self, key):
+ # GH 31117
+ idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
+ s = pd.Series(range(len(idx)), index=idx)
+
+ msg = str(key)
+ with pytest.raises(InvalidIndexError, match=msg):
+ with tm.assert_produces_warning(FutureWarning):
+ idx.get_value(s, key)
+
def test_dir():
# GH#27571 dir(interval_index) should not raise
| ensure InvalidIndexError is raised when non-scalar is passed as key to
get_loc and get_value methods for IntervalIndex
- [X] closes #31117
- [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/33938 | 2020-05-02T03:13:12Z | 2020-05-09T20:22:04Z | 2020-05-09T20:22:04Z | 2020-05-10T01:54:45Z |
PERF: use fastpaths for is_period_dtype checks | diff --git a/pandas/_testing.py b/pandas/_testing.py
index eb4eb86c78b2d..74c4c661b4b83 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1519,11 +1519,13 @@ def box_expected(expected, box_cls, transpose=True):
def to_array(obj):
# temporary implementation until we get pd.array in place
- if is_period_dtype(obj):
+ dtype = getattr(obj, "dtype", None)
+
+ if is_period_dtype(dtype):
return period_array(obj)
- elif is_datetime64_dtype(obj) or is_datetime64tz_dtype(obj):
+ elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
return DatetimeArray._from_sequence(obj)
- elif is_timedelta64_dtype(obj):
+ elif is_timedelta64_dtype(dtype):
return TimedeltaArray._from_sequence(obj)
else:
return np.array(obj)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index ce22c3f5416fa..449d9ad8301e4 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -11,7 +11,7 @@
from pandas._libs import Timestamp, algos, hashtable as htable, lib
from pandas._libs.tslib import iNaT
-from pandas._typing import AnyArrayLike
+from pandas._typing import AnyArrayLike, DtypeObj
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import (
@@ -126,20 +126,21 @@ def _ensure_data(values, dtype=None):
return ensure_object(values), "object"
# datetimelike
- if needs_i8_conversion(values) or needs_i8_conversion(dtype):
- if is_period_dtype(values) or is_period_dtype(dtype):
+ vals_dtype = getattr(values, "dtype", None)
+ if needs_i8_conversion(vals_dtype) or needs_i8_conversion(dtype):
+ if is_period_dtype(vals_dtype) or is_period_dtype(dtype):
from pandas import PeriodIndex
values = PeriodIndex(values)
dtype = values.dtype
- elif is_timedelta64_dtype(values) or is_timedelta64_dtype(dtype):
+ elif is_timedelta64_dtype(vals_dtype) or is_timedelta64_dtype(dtype):
from pandas import TimedeltaIndex
values = TimedeltaIndex(values)
dtype = values.dtype
else:
# Datetime
- if values.ndim > 1 and is_datetime64_ns_dtype(values):
+ if values.ndim > 1 and is_datetime64_ns_dtype(vals_dtype):
# Avoid calling the DatetimeIndex constructor as it is 1D only
# Note: this is reached by DataFrame.rank calls GH#27027
# TODO(EA2D): special case not needed with 2D EAs
@@ -154,7 +155,7 @@ def _ensure_data(values, dtype=None):
return values.asi8, dtype
- elif is_categorical_dtype(values) and (
+ elif is_categorical_dtype(vals_dtype) and (
is_categorical_dtype(dtype) or dtype is None
):
values = values.codes
@@ -1080,7 +1081,7 @@ def nsmallest(self):
return self.compute("nsmallest")
@staticmethod
- def is_valid_dtype_n_method(dtype) -> bool:
+ def is_valid_dtype_n_method(dtype: DtypeObj) -> bool:
"""
Helper function to determine if dtype is valid for
nsmallest/nlargest methods
@@ -1863,7 +1864,7 @@ def diff(arr, n: int, axis: int = 0, stacklevel=3):
is_timedelta = False
is_bool = False
- if needs_i8_conversion(arr):
+ if needs_i8_conversion(arr.dtype):
dtype = np.float64
arr = arr.view("i8")
na = iNaT
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index de401368d55d7..de12d96556263 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1424,7 +1424,7 @@ def _internal_get_values(self):
Index if datetime / periods.
"""
# if we are a datetime and period index, return Index to keep metadata
- if needs_i8_conversion(self.categories):
+ if needs_i8_conversion(self.categories.dtype):
return self.categories.take(self._codes, fill_value=np.nan)
elif is_integer_dtype(self.categories) and -1 in self._codes:
return self.categories.astype("object").take(self._codes, fill_value=np.nan)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index e07e2da164cac..25ac3e445822e 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -782,7 +782,7 @@ def _validate_searchsorted_value(self, value):
elif is_list_like(value) and not isinstance(value, type(self)):
value = array(value)
- if not type(self)._is_recognized_dtype(value):
+ if not type(self)._is_recognized_dtype(value.dtype):
raise TypeError(
"searchsorted requires compatible dtype or scalar, "
f"not {type(value).__name__}"
@@ -806,7 +806,7 @@ def _validate_setitem_value(self, value):
except ValueError:
pass
- if not type(self)._is_recognized_dtype(value):
+ if not type(self)._is_recognized_dtype(value.dtype):
raise TypeError(
"setitem requires compatible dtype or scalar, "
f"not {type(value).__name__}"
@@ -1024,7 +1024,7 @@ def fillna(self, value=None, method=None, limit=None):
func = missing.backfill_1d
values = self._data
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
# For PeriodArray self._data is i8, which gets copied
# by `func`. Otherwise we need to make a copy manually
# to avoid modifying `self` in-place.
@@ -1109,10 +1109,7 @@ def _validate_frequency(cls, index, freq, **kwargs):
freq : DateOffset
The frequency to validate
"""
- if is_period_dtype(cls):
- # Frequency validation is not meaningful for Period Array/Index
- return None
-
+ # TODO: this is not applicable to PeriodArray, move to correct Mixin
inferred = index.inferred_freq
if index.size == 0 or inferred == freq.freqstr:
return None
@@ -1253,7 +1250,7 @@ def _add_nat(self):
"""
Add pd.NaT to self
"""
- if is_period_dtype(self):
+ if is_period_dtype(self.dtype):
raise TypeError(
f"Cannot add {type(self).__name__} and {type(NaT).__name__}"
)
@@ -1293,7 +1290,7 @@ def _sub_period_array(self, other):
result : np.ndarray[object]
Array of DateOffset objects; nulls represented by NaT.
"""
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
raise TypeError(
f"cannot subtract {other.dtype}-dtype from {type(self).__name__}"
)
@@ -1398,7 +1395,7 @@ def __add__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
raise integer_op_not_supported(self)
result = self._time_shift(other)
@@ -1413,7 +1410,7 @@ def __add__(self, other):
# DatetimeIndex, ndarray[datetime64]
return self._add_datetime_arraylike(other)
elif is_integer_dtype(other):
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
raise integer_op_not_supported(self)
result = self._addsub_int_array(other, operator.add)
else:
@@ -1437,6 +1434,8 @@ def __radd__(self, other):
@unpack_zerodim_and_defer("__sub__")
def __sub__(self, other):
+ other_dtype = getattr(other, "dtype", None)
+
# scalar others
if other is NaT:
result = self._sub_nat()
@@ -1450,7 +1449,7 @@ def __sub__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
raise integer_op_not_supported(self)
result = self._time_shift(-other)
@@ -1467,11 +1466,11 @@ def __sub__(self, other):
elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other):
# DatetimeIndex, ndarray[datetime64]
result = self._sub_datetime_arraylike(other)
- elif is_period_dtype(other):
+ elif is_period_dtype(other_dtype):
# PeriodIndex
result = self._sub_period_array(other)
- elif is_integer_dtype(other):
- if not is_period_dtype(self):
+ elif is_integer_dtype(other_dtype):
+ if not is_period_dtype(self.dtype):
raise integer_op_not_supported(self)
result = self._addsub_int_array(other, operator.sub)
else:
@@ -1520,7 +1519,7 @@ def __iadd__(self, other):
result = self + other
self[:] = result[:]
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
# restore freq, which is invalidated by setitem
self._freq = result._freq
return self
@@ -1529,7 +1528,7 @@ def __isub__(self, other):
result = self - other
self[:] = result[:]
- if not is_period_dtype(self):
+ if not is_period_dtype(self.dtype):
# restore freq, which is invalidated by setitem
self._freq = result._freq
return self
@@ -1621,7 +1620,7 @@ def mean(self, skipna=True):
-----
mean is only defined for Datetime and Timedelta dtypes, not for Period.
"""
- if is_period_dtype(self):
+ if is_period_dtype(self.dtype):
# See discussion in GH#24757
raise TypeError(
f"mean is not implemented for {type(self).__name__} since the "
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 1460a2e762771..88ee6d010e52a 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -828,9 +828,11 @@ def period_array(
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC]
"""
- if is_datetime64_dtype(data):
+ data_dtype = getattr(data, "dtype", None)
+
+ if is_datetime64_dtype(data_dtype):
return PeriodArray._from_datetime64(data, freq)
- if is_period_dtype(data):
+ if is_period_dtype(data_dtype):
return PeriodArray(data, freq)
# other iterable of some kind
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 87ff9a78909dd..048fd7adf55b1 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -424,7 +424,7 @@ def array_equivalent(left, right, strict_nan: bool = False) -> bool:
return True
# NaNs can occur in float and complex arrays.
- if is_float_dtype(left) or is_complex_dtype(left):
+ if is_float_dtype(left.dtype) or is_complex_dtype(left.dtype):
# empty
if not (np.prod(left.shape) and np.prod(right.shape)):
@@ -435,7 +435,7 @@ def array_equivalent(left, right, strict_nan: bool = False) -> bool:
# GH#29553 avoid numpy deprecation warning
return False
- elif needs_i8_conversion(left) or needs_i8_conversion(right):
+ elif needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype):
# datetime64, timedelta64, Period
if not is_dtype_equal(left.dtype, right.dtype):
return False
@@ -460,7 +460,7 @@ def _infer_fill_value(val):
if not is_list_like(val):
val = [val]
val = np.array(val, copy=False)
- if needs_i8_conversion(val):
+ if needs_i8_conversion(val.dtype):
return np.array("NaT", dtype=val.dtype)
elif is_object_dtype(val.dtype):
dtype = lib.infer_dtype(ensure_object(val), skipna=False)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1bff17b40433d..a46b9c8d1661c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5916,7 +5916,7 @@ def extract_values(arr):
if isinstance(arr, (ABCIndexClass, ABCSeries)):
arr = arr._values
- if needs_i8_conversion(arr):
+ if needs_i8_conversion(arr.dtype):
if is_extension_array_dtype(arr.dtype):
arr = arr.asi8
else:
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 90c9f4562515a..db2264db438f4 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -49,7 +49,7 @@ def _get_values(self):
elif is_timedelta64_dtype(data.dtype):
return TimedeltaIndex(data, copy=False, name=self.name)
- elif is_period_dtype(data):
+ elif is_period_dtype(data.dtype):
return PeriodArray(data, copy=False)
raise TypeError(
@@ -449,7 +449,7 @@ def __new__(cls, data: "Series"):
return DatetimeProperties(data, orig)
elif is_timedelta64_dtype(data.dtype):
return TimedeltaProperties(data, orig)
- elif is_period_dtype(data):
+ elif is_period_dtype(data.dtype):
return PeriodProperties(data, orig)
raise AttributeError("Can only use .dt accessor with datetimelike values")
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 3f18f69149658..e26dc5b9e4fb3 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -118,7 +118,7 @@ def __array_wrap__(self, result, context=None):
return result
attrs = self._get_attributes_dict()
- if not is_period_dtype(self) and attrs["freq"]:
+ if not is_period_dtype(self.dtype) and attrs["freq"]:
# no need to infer if freq is None
attrs["freq"] = "infer"
return Index(result, **attrs)
@@ -542,7 +542,7 @@ def delete(self, loc):
new_i8s = np.delete(self.asi8, loc)
freq = None
- if is_period_dtype(self):
+ if is_period_dtype(self.dtype):
freq = self.freq
elif is_integer(loc):
if loc in (0, -len(self), -1, len(self) - 1):
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index afca4ca86bd3f..39df7ae3c9b60 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2673,13 +2673,13 @@ def get_block_type(values, dtype=None):
elif is_categorical_dtype(values.dtype):
cls = CategoricalBlock
elif issubclass(vtype, np.datetime64):
- assert not is_datetime64tz_dtype(values)
+ assert not is_datetime64tz_dtype(values.dtype)
cls = DatetimeBlock
- elif is_datetime64tz_dtype(values):
+ elif is_datetime64tz_dtype(values.dtype):
cls = DatetimeTZBlock
elif is_interval_dtype(dtype) or is_period_dtype(dtype):
cls = ObjectValuesExtensionBlock
- elif is_extension_array_dtype(values):
+ elif is_extension_array_dtype(values.dtype):
cls = ExtensionBlock
elif issubclass(vtype, np.floating):
cls = FloatBlock
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 7b5399ca85e79..79bbef5fa5505 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -266,7 +266,7 @@ def interpolate_1d(
if method in ("values", "index"):
inds = np.asarray(xvalues)
# hack for DatetimeIndex, #1646
- if needs_i8_conversion(inds.dtype.type):
+ if needs_i8_conversion(inds.dtype):
inds = inds.view(np.int64)
if inds.dtype == np.object_:
inds = lib.maybe_convert_objects(inds)
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 32b05872ded3f..49920815c3439 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -287,7 +287,7 @@ def _get_values(
dtype = values.dtype
- if needs_i8_conversion(values):
+ if needs_i8_conversion(values.dtype):
# changing timedelta64/datetime64 to int64 needs to happen after
# finding `mask` above
values = np.asarray(values.view("i8"))
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 882e3e0a649cc..133fba0246497 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -232,10 +232,10 @@ def get_new_values(self, values, fill_value=None):
# we need to convert to a basic dtype
# and possibly coerce an input to our output dtype
# e.g. ints -> floats
- if needs_i8_conversion(values):
+ if needs_i8_conversion(values.dtype):
sorted_values = sorted_values.view("i8")
new_values = new_values.view("i8")
- elif is_bool_dtype(values):
+ elif is_bool_dtype(values.dtype):
sorted_values = sorted_values.astype("object")
new_values = new_values.astype("object")
else:
@@ -253,7 +253,7 @@ def get_new_values(self, values, fill_value=None):
)
# reconstruct dtype if needed
- if needs_i8_conversion(values):
+ if needs_i8_conversion(values.dtype):
new_values = new_values.view(values.dtype)
return new_values, new_mask
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index eb7f15c78b671..ac6f9ff372601 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -306,7 +306,7 @@ def __init__(
if len(timedeltas):
obj[timedeltas] = obj[timedeltas].applymap(lambda x: x.isoformat())
# Convert PeriodIndex to datetimes before serializing
- if is_period_dtype(obj.index):
+ if is_period_dtype(obj.index.dtype):
obj.index = obj.index.to_timestamp()
# exclude index from obj if index=False
diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py
index 50686594a7576..239ff6241aab0 100644
--- a/pandas/io/json/_table_schema.py
+++ b/pandas/io/json/_table_schema.py
@@ -105,22 +105,16 @@ def convert_pandas_type_to_json_field(arr):
name = arr.name
field = {"name": name, "type": as_json_table_type(dtype)}
- if is_categorical_dtype(arr):
- if hasattr(arr, "categories"):
- cats = arr.categories
- ordered = arr.ordered
- else:
- cats = arr.cat.categories
- ordered = arr.cat.ordered
+ if is_categorical_dtype(dtype):
+ cats = dtype.categories
+ ordered = dtype.ordered
+
field["constraints"] = {"enum": list(cats)}
field["ordered"] = ordered
- elif is_period_dtype(arr):
- field["freq"] = arr.freqstr
- elif is_datetime64tz_dtype(arr):
- if hasattr(arr, "dt"):
- field["tz"] = arr.dt.tz.zone
- else:
- field["tz"] = arr.tz.zone
+ elif is_period_dtype(dtype):
+ field["freq"] = dtype.freq.freqstr
+ elif is_datetime64tz_dtype(dtype):
+ field["tz"] = dtype.tz.zone
return field
diff --git a/pandas/tests/base/test_fillna.py b/pandas/tests/base/test_fillna.py
index 5e50a9e2d1c7f..630ecdacd91d1 100644
--- a/pandas/tests/base/test_fillna.py
+++ b/pandas/tests/base/test_fillna.py
@@ -50,7 +50,7 @@ def test_fillna_null(null_obj, index_or_series_obj):
values = obj.values
fill_value = values[0]
expected = values.copy()
- if needs_i8_conversion(obj):
+ if needs_i8_conversion(obj.dtype):
values[0:2] = iNaT
expected[0:2] = fill_value
else:
diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py
index c6225c9b5ca64..eca402af252f8 100644
--- a/pandas/tests/base/test_unique.py
+++ b/pandas/tests/base/test_unique.py
@@ -43,7 +43,7 @@ def test_unique_null(null_obj, index_or_series_obj):
pytest.skip(f"MultiIndex can't hold '{null_obj}'")
values = obj.values
- if needs_i8_conversion(obj):
+ if needs_i8_conversion(obj.dtype):
values[0:2] = iNaT
else:
values[0:2] = null_obj
@@ -89,7 +89,7 @@ def test_nunique_null(null_obj, index_or_series_obj):
pytest.skip(f"MultiIndex can't hold '{null_obj}'")
values = obj.values
- if needs_i8_conversion(obj):
+ if needs_i8_conversion(obj.dtype):
values[0:2] = iNaT
else:
values[0:2] = null_obj
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
index d45feaff68dde..2514b11613ef6 100644
--- a/pandas/tests/base/test_value_counts.py
+++ b/pandas/tests/base/test_value_counts.py
@@ -55,7 +55,7 @@ def test_value_counts_null(null_obj, index_or_series_obj):
pytest.skip(f"MultiIndex can't hold '{null_obj}'")
values = obj.values
- if needs_i8_conversion(obj):
+ if needs_i8_conversion(obj.dtype):
values[0:2] = iNaT
else:
values[0:2] = null_obj
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 01d72670f37aa..a08001e042f36 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -215,10 +215,10 @@ def test_get_unique_index(self, indices):
if not indices._can_hold_na:
pytest.skip("Skip na-check if index cannot hold na")
- if is_period_dtype(indices):
+ if is_period_dtype(indices.dtype):
vals = indices[[0] * 5]._data
vals[0] = pd.NaT
- elif needs_i8_conversion(indices):
+ elif needs_i8_conversion(indices.dtype):
vals = indices.asi8[[0] * 5]
vals[0] = iNaT
else:
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 12320cd52cec8..abd4bf288bd9e 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -272,12 +272,15 @@ def infer_freq(index, warn: bool = True) -> Optional[str]:
index = values
inferer: _FrequencyInferer
- if is_period_dtype(index):
+
+ if not hasattr(index, "dtype"):
+ pass
+ elif is_period_dtype(index.dtype):
raise TypeError(
"PeriodIndex given. Check the `freq` attribute "
"instead of using infer_freq."
)
- elif is_timedelta64_dtype(index):
+ elif is_timedelta64_dtype(index.dtype):
# Allow TimedeltaIndex and TimedeltaArray
inferer = _TimedeltaFrequencyInferer(index, warn=warn)
return inferer.get_freq()
| This gets most of the is_period_dtype and needs_i8_conversion checks. There are a few left in reshape.merge where i need to track down what type of objects we're working with.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33937 | 2020-05-02T02:45:12Z | 2020-05-02T11:05:55Z | 2020-05-02T11:05:54Z | 2020-05-02T14:57:19Z |
REF: move bits of offsets to liboffsets, de-privatize | diff --git a/asv_bench/benchmarks/io/parsers.py b/asv_bench/benchmarks/io/parsers.py
index c5e099bd44eac..ec3eddfff7184 100644
--- a/asv_bench/benchmarks/io/parsers.py
+++ b/asv_bench/benchmarks/io/parsers.py
@@ -2,7 +2,7 @@
try:
from pandas._libs.tslibs.parsing import (
- _concat_date_cols,
+ concat_date_cols,
_does_string_look_like_datetime,
)
except ImportError:
@@ -39,4 +39,4 @@ def setup(self, value, dim):
)
def time_check_concat(self, value, dim):
- _concat_date_cols(self.object)
+ concat_date_cols(self.object)
diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx
index d60f5cfd3f8c1..31747f96399ee 100644
--- a/pandas/_libs/tslibs/frequencies.pyx
+++ b/pandas/_libs/tslibs/frequencies.pyx
@@ -175,13 +175,13 @@ cpdef get_freq_code(freqstr):
if is_integer_object(freqstr):
return freqstr, 1
- base, stride = _base_and_stride(freqstr)
+ base, stride = base_and_stride(freqstr)
code = _period_str_to_code(base)
return code, stride
-cpdef _base_and_stride(str freqstr):
+cpdef base_and_stride(str freqstr):
"""
Return base freq and stride info from string representation
@@ -267,7 +267,7 @@ cpdef str get_base_alias(freqstr):
-------
base_alias : str
"""
- return _base_and_stride(freqstr)[0]
+ return base_and_stride(freqstr)[0]
cpdef int get_to_timestamp_base(int base):
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 4c7d03d51e909..3dfaa36888f62 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -2,6 +2,7 @@ import cython
import time
from typing import Any
+import warnings
from cpython.datetime cimport (PyDateTime_IMPORT,
PyDateTime_Check,
PyDelta_Check,
@@ -103,7 +104,7 @@ def as_datetime(obj):
return obj
-cpdef bint _is_normalized(dt):
+cpdef bint is_normalized(dt):
if (dt.hour != 0 or dt.minute != 0 or dt.second != 0 or
dt.microsecond != 0 or getattr(dt, 'nanosecond', 0) != 0):
return False
@@ -230,7 +231,7 @@ def _get_calendar(weekmask, holidays, calendar):
holidays = holidays + calendar.holidays().tolist()
except AttributeError:
pass
- holidays = [_to_dt64D(dt) for dt in holidays]
+ holidays = [to_dt64D(dt) for dt in holidays]
holidays = tuple(sorted(holidays))
kwargs = {'weekmask': weekmask}
@@ -241,7 +242,7 @@ def _get_calendar(weekmask, holidays, calendar):
return busdaycalendar, holidays
-def _to_dt64D(dt):
+def to_dt64D(dt):
# Currently
# > np.datetime64(dt.datetime(2013,5,1),dtype='datetime64[D]')
# numpy.datetime64('2013-05-01T02:00:00.000000+0200')
@@ -264,7 +265,7 @@ def _to_dt64D(dt):
# Validation
-def _validate_business_time(t_input):
+def validate_business_time(t_input):
if isinstance(t_input, str):
try:
t = time.strptime(t_input, '%H:%M')
@@ -440,6 +441,9 @@ class _BaseOffset:
# that allows us to use methods that can go in a `cdef class`
return self * 1
+ # ------------------------------------------------------------------
+ # Name and Rendering Methods
+
def __repr__(self) -> str:
className = getattr(self, '_outputName', type(self).__name__)
@@ -455,6 +459,44 @@ class _BaseOffset:
out = f'<{n_str}{className}{plural}{self._repr_attrs()}>'
return out
+ @property
+ def name(self) -> str:
+ return self.rule_code
+
+ @property
+ def _prefix(self) -> str:
+ raise NotImplementedError("Prefix not defined")
+
+ @property
+ def rule_code(self) -> str:
+ return self._prefix
+
+ @property
+ def freqstr(self) -> str:
+ try:
+ code = self.rule_code
+ except NotImplementedError:
+ return str(repr(self))
+
+ if self.n != 1:
+ fstr = f"{self.n}{code}"
+ else:
+ fstr = code
+
+ try:
+ if self._offset:
+ fstr += self._offset_str()
+ except AttributeError:
+ # TODO: standardize `_offset` vs `offset` naming convention
+ pass
+
+ return fstr
+
+ def _offset_str(self) -> str:
+ return ""
+
+ # ------------------------------------------------------------------
+
def _get_offset_day(self, datetime other):
# subclass must implement `_day_opt`; calling from the base class
# will raise NotImplementedError.
@@ -530,6 +572,26 @@ class _BaseOffset:
return state
+ @property
+ def nanos(self):
+ raise ValueError(f"{self} is a non-fixed frequency")
+
+ def onOffset(self, dt) -> bool:
+ warnings.warn(
+ "onOffset is a deprecated, use is_on_offset instead",
+ FutureWarning,
+ stacklevel=1,
+ )
+ return self.is_on_offset(dt)
+
+ def isAnchored(self) -> bool:
+ warnings.warn(
+ "isAnchored is a deprecated, use is_anchored instead",
+ FutureWarning,
+ stacklevel=1,
+ )
+ return self.is_anchored()
+
class BaseOffset(_BaseOffset):
# Here we add __rfoo__ methods that don't play well with cdef classes
@@ -564,6 +626,49 @@ class _Tick:
return _wrap_timedelta_result(result)
+class BusinessMixin:
+ """
+ Mixin to business types to provide related functions.
+ """
+
+ @property
+ def offset(self):
+ """
+ Alias for self._offset.
+ """
+ # Alias for backward compat
+ return self._offset
+
+ def _repr_attrs(self) -> str:
+ if self.offset:
+ attrs = [f"offset={repr(self.offset)}"]
+ else:
+ attrs = []
+ out = ""
+ if attrs:
+ out += ": " + ", ".join(attrs)
+ return out
+
+
+class CustomMixin:
+ """
+ Mixin for classes that define and validate calendar, holidays,
+ and weekdays attributes.
+ """
+
+ def __init__(self, weekmask, holidays, calendar):
+ calendar, holidays = _get_calendar(
+ weekmask=weekmask, holidays=holidays, calendar=calendar
+ )
+ # Custom offset instances are identified by the
+ # following two attributes. See DateOffset._params()
+ # holidays, weekmask
+
+ object.__setattr__(self, "weekmask", weekmask)
+ object.__setattr__(self, "holidays", holidays)
+ object.__setattr__(self, "calendar", calendar)
+
+
# ----------------------------------------------------------------------
# RelativeDelta Arithmetic
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index 1b980aea372e2..5fda0db4891c3 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -938,7 +938,7 @@ cdef inline object convert_to_unicode(object item, bint keep_trivial_numbers):
@cython.wraparound(False)
@cython.boundscheck(False)
-def _concat_date_cols(tuple date_cols, bint keep_trivial_numbers=True):
+def concat_date_cols(tuple date_cols, bint keep_trivial_numbers=True):
"""
Concatenates elements from numpy arrays in `date_cols` into strings.
@@ -957,7 +957,7 @@ def _concat_date_cols(tuple date_cols, bint keep_trivial_numbers=True):
--------
>>> dates=np.array(['3/31/2019', '4/31/2019'], dtype=object)
>>> times=np.array(['11:20', '10:45'], dtype=object)
- >>> result = _concat_date_cols((dates, times))
+ >>> result = concat_date_cols((dates, times))
>>> result
array(['3/31/2019 11:20', '4/31/2019 10:45'], dtype=object)
"""
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index c4a7df0017619..5cf8fedbf0431 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1685,7 +1685,7 @@ cdef class _Period:
resampled : Period
"""
freq = self._maybe_convert_freq(freq)
- how = _validate_end_alias(how)
+ how = validate_end_alias(how)
base1, mult1 = get_freq_code(self.freq)
base2, mult2 = get_freq_code(freq)
@@ -1758,7 +1758,7 @@ cdef class _Period:
"""
if freq is not None:
freq = self._maybe_convert_freq(freq)
- how = _validate_end_alias(how)
+ how = validate_end_alias(how)
end = how == 'E'
if end:
@@ -2509,7 +2509,7 @@ def quarter_to_myear(year: int, quarter: int, freq):
return year, month
-def _validate_end_alias(how):
+def validate_end_alias(how):
how_dict = {'S': 'S', 'E': 'E',
'START': 'S', 'FINISH': 'E',
'BEGIN': 'S', 'END': 'E'}
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index e3fbb906ed6b1..f7408e69f7dec 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1115,7 +1115,7 @@ def to_period(self, freq=None):
# https://github.com/pandas-dev/pandas/issues/33358
if res is None:
- base, stride = libfrequencies._base_and_stride(freq)
+ base, stride = libfrequencies.base_and_stride(freq)
res = f"{stride}{base}"
freq = res
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index b7dfcd4cb188c..c00230c3b5ab3 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -432,7 +432,7 @@ def to_timestamp(self, freq=None, how="start"):
"""
from pandas.core.arrays import DatetimeArray
- how = libperiod._validate_end_alias(how)
+ how = libperiod.validate_end_alias(how)
end = how == "E"
if end:
@@ -524,7 +524,7 @@ def asfreq(self, freq=None, how: str = "E") -> "PeriodArray":
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]', freq='M')
"""
- how = libperiod._validate_end_alias(how)
+ how = libperiod.validate_end_alias(how)
freq = Period._maybe_convert_freq(freq)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index f289db39347ae..aca2f9f5ac5bb 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -3264,7 +3264,7 @@ def _make_date_converter(
):
def converter(*date_cols):
if date_parser is None:
- strs = parsing._concat_date_cols(date_cols)
+ strs = parsing.concat_date_cols(date_cols)
try:
return tools.to_datetime(
@@ -3292,7 +3292,7 @@ def converter(*date_cols):
try:
return tools.to_datetime(
parsing.try_parse_dates(
- parsing._concat_date_cols(date_cols),
+ parsing.concat_date_cols(date_cols),
parser=date_parser,
dayfirst=dayfirst,
),
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index e11bbb89c885c..ed947755e3419 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -81,7 +81,7 @@ def date_parser(*date_cols):
-------
parsed : Series
"""
- return parsing.try_parse_dates(parsing._concat_date_cols(date_cols))
+ return parsing.try_parse_dates(parsing.concat_date_cols(date_cols))
result = parser.read_csv(
StringIO(data),
@@ -208,7 +208,7 @@ def test_concat_date_col_fail(container, dim):
date_cols = tuple(container([value]) for _ in range(dim))
with pytest.raises(ValueError, match=msg):
- parsing._concat_date_cols(date_cols)
+ parsing.concat_date_cols(date_cols)
@pytest.mark.parametrize("keep_date_col", [True, False])
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 12320cd52cec8..df0d71e8c80c5 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -124,7 +124,7 @@ def to_offset(freq) -> Optional[DateOffset]:
stride = freq[1]
if isinstance(stride, str):
name, stride = stride, name
- name, _ = libfreqs._base_and_stride(name)
+ name, _ = libfreqs.base_and_stride(name)
delta = _get_offset(name) * stride
elif isinstance(freq, timedelta):
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 286ee91bc7d4f..c1ab752bf9550 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -2,7 +2,6 @@
import functools
import operator
from typing import Any, Optional
-import warnings
from dateutil.easter import easter
import numpy as np
@@ -24,13 +23,14 @@
from pandas._libs.tslibs.offsets import (
ApplyTypeError,
BaseOffset,
- _get_calendar,
- _is_normalized,
- _to_dt64D,
+ BusinessMixin,
+ CustomMixin,
apply_index_wraps,
as_datetime,
+ is_normalized,
roll_yearday,
shift_month,
+ to_dt64D,
)
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, Substitution, cache_readonly
@@ -249,6 +249,7 @@ def __add__(date):
"""
_params = cache_readonly(BaseOffset._params.fget)
+ freqstr = cache_readonly(BaseOffset.freqstr.fget)
_use_relativedelta = False
_adjust_dst = False
_attributes = frozenset(["n", "normalize"] + list(liboffsets.relativedelta_kwds))
@@ -366,22 +367,6 @@ def is_anchored(self) -> bool:
# if there were a canonical docstring for what is_anchored means.
return self.n == 1
- def onOffset(self, dt):
- warnings.warn(
- "onOffset is a deprecated, use is_on_offset instead",
- FutureWarning,
- stacklevel=2,
- )
- return self.is_on_offset(dt)
-
- def isAnchored(self) -> bool:
- warnings.warn(
- "isAnchored is a deprecated, use is_anchored instead",
- FutureWarning,
- stacklevel=2,
- )
- return self.is_anchored()
-
# TODO: Combine this with BusinessMixin version by defining a whitelisted
# set of attributes on each object rather than the existing behavior of
# iterating over internal ``__dict__``
@@ -400,10 +385,6 @@ def _repr_attrs(self) -> str:
out += ": " + ", ".join(attrs)
return out
- @property
- def name(self) -> str:
- return self.rule_code
-
def rollback(self, dt):
"""
Roll provided date backward to next offset only if not on offset.
@@ -433,7 +414,7 @@ def rollforward(self, dt):
return dt
def is_on_offset(self, dt):
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
# TODO, see #1395
if type(self) == DateOffset or isinstance(self, Tick):
@@ -446,43 +427,6 @@ def is_on_offset(self, dt):
b = (dt + self) - self
return a == b
- # way to get around weirdness with rule_code
- @property
- def _prefix(self) -> str:
- raise NotImplementedError("Prefix not defined")
-
- @property
- def rule_code(self) -> str:
- return self._prefix
-
- @cache_readonly
- def freqstr(self) -> str:
- try:
- code = self.rule_code
- except NotImplementedError:
- return repr(self)
-
- if self.n != 1:
- fstr = f"{self.n}{code}"
- else:
- fstr = code
-
- try:
- if self._offset:
- fstr += self._offset_str()
- except AttributeError:
- # TODO: standardize `_offset` vs `offset` naming convention
- pass
-
- return fstr
-
- def _offset_str(self) -> str:
- return ""
-
- @property
- def nanos(self):
- raise ValueError(f"{self} is a non-fixed frequency")
-
class SingleConstructorOffset(DateOffset):
@classmethod
@@ -493,49 +437,6 @@ def _from_name(cls, suffix=None):
return cls()
-class _CustomMixin:
- """
- Mixin for classes that define and validate calendar, holidays,
- and weekdays attributes.
- """
-
- def __init__(self, weekmask, holidays, calendar):
- calendar, holidays = _get_calendar(
- weekmask=weekmask, holidays=holidays, calendar=calendar
- )
- # Custom offset instances are identified by the
- # following two attributes. See DateOffset._params()
- # holidays, weekmask
-
- object.__setattr__(self, "weekmask", weekmask)
- object.__setattr__(self, "holidays", holidays)
- object.__setattr__(self, "calendar", calendar)
-
-
-class BusinessMixin:
- """
- Mixin to business types to provide related functions.
- """
-
- @property
- def offset(self):
- """
- Alias for self._offset.
- """
- # Alias for backward compat
- return self._offset
-
- def _repr_attrs(self) -> str:
- if self.offset:
- attrs = [f"offset={repr(self.offset)}"]
- else:
- attrs = []
- out = ""
- if attrs:
- out += ": " + ", ".join(attrs)
- return out
-
-
class BusinessDay(BusinessMixin, SingleConstructorOffset):
"""
DateOffset subclass representing possibly n business days.
@@ -643,7 +544,7 @@ def apply_index(self, i):
return result
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
return dt.weekday() < 5
@@ -661,8 +562,8 @@ def __init__(self, start="09:00", end="17:00", offset=timedelta(0)):
if not len(end):
raise ValueError("Must include at least 1 end time")
- start = np.array([liboffsets._validate_business_time(x) for x in start])
- end = np.array([liboffsets._validate_business_time(x) for x in end])
+ start = np.array([liboffsets.validate_business_time(x) for x in start])
+ end = np.array([liboffsets.validate_business_time(x) for x in end])
# Validation of input
if len(start) != len(end):
@@ -889,7 +790,7 @@ def apply(self, other):
# adjust by business days first
if bd != 0:
- if isinstance(self, _CustomMixin): # GH 30593
+ if isinstance(self, CustomMixin): # GH 30593
skip_bd = CustomBusinessDay(
n=bd,
weekmask=self.weekmask,
@@ -949,7 +850,7 @@ def apply(self, other):
raise ApplyTypeError("Only know how to combine business hour with datetime")
def is_on_offset(self, dt):
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
if dt.tzinfo is not None:
@@ -964,7 +865,7 @@ def _is_on_offset(self, dt):
"""
Slight speedups using calculated values.
"""
- # if self.normalize and not _is_normalized(dt):
+ # if self.normalize and not is_normalized(dt):
# return False
# Valid BH can be on the different BusinessDay during midnight
# Distinguish by the time spent from previous opening time
@@ -1009,7 +910,7 @@ def __init__(
super().__init__(start=start, end=end, offset=offset)
-class CustomBusinessDay(_CustomMixin, BusinessDay):
+class CustomBusinessDay(CustomMixin, BusinessDay):
"""
DateOffset subclass representing custom business days excluding holidays.
@@ -1044,7 +945,7 @@ def __init__(
BaseOffset.__init__(self, n, normalize)
object.__setattr__(self, "_offset", offset)
- _CustomMixin.__init__(self, weekmask, holidays, calendar)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
@apply_wraps
def apply(self, other):
@@ -1080,13 +981,13 @@ def apply_index(self, i):
raise NotImplementedError
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
- day64 = _to_dt64D(dt)
+ day64 = to_dt64D(dt)
return np.is_busday(day64, busdaycal=self.calendar)
-class CustomBusinessHour(_CustomMixin, BusinessHourMixin, SingleConstructorOffset):
+class CustomBusinessHour(CustomMixin, BusinessHourMixin, SingleConstructorOffset):
"""
DateOffset subclass representing possibly n custom business days.
"""
@@ -1111,7 +1012,7 @@ def __init__(
BaseOffset.__init__(self, n, normalize)
object.__setattr__(self, "_offset", offset)
- _CustomMixin.__init__(self, weekmask, holidays, calendar)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
BusinessHourMixin.__init__(self, start=start, end=end, offset=offset)
@@ -1126,7 +1027,7 @@ class MonthOffset(SingleConstructorOffset):
__init__ = BaseOffset.__init__
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
return dt.day == self._get_offset_day(dt)
@@ -1178,7 +1079,7 @@ class BusinessMonthBegin(MonthOffset):
_day_opt = "business_start"
-class _CustomBusinessMonth(_CustomMixin, BusinessMixin, MonthOffset):
+class _CustomBusinessMonth(CustomMixin, BusinessMixin, MonthOffset):
"""
DateOffset subclass representing custom business month(s).
@@ -1220,7 +1121,7 @@ def __init__(
BaseOffset.__init__(self, n, normalize)
object.__setattr__(self, "_offset", offset)
- _CustomMixin.__init__(self, weekmask, holidays, calendar)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
@cache_readonly
def cbday_roll(self):
@@ -1409,7 +1310,7 @@ class SemiMonthEnd(SemiMonthOffset):
_min_day_of_month = 1
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
days_in_month = ccalendar.get_days_in_month(dt.year, dt.month)
return dt.day in (self.day_of_month, days_in_month)
@@ -1467,7 +1368,7 @@ class SemiMonthBegin(SemiMonthOffset):
_prefix = "SMS"
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
return dt.day in (1, self.day_of_month)
@@ -1606,7 +1507,7 @@ def _end_apply_index(self, dtindex):
return base + off + Timedelta(1, "ns") - Timedelta(1, "D")
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
elif self.weekday is None:
return True
@@ -1649,7 +1550,7 @@ def apply(self, other):
return liboffsets.shift_day(shifted, to_day - shifted.day)
def is_on_offset(self, dt):
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
return dt.day == self._get_offset_day(dt)
@@ -1848,7 +1749,7 @@ def apply(self, other):
return shift_month(other, months, self._day_opt)
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
mod_month = (dt.month - self.startingMonth) % 3
return mod_month == 0 and dt.day == self._get_offset_day(dt)
@@ -1943,7 +1844,7 @@ def apply_index(self, dtindex):
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):
+ if self.normalize and not is_normalized(dt):
return False
return dt.month == self.month and dt.day == self._get_offset_day(dt)
@@ -2088,7 +1989,7 @@ def is_anchored(self) -> bool:
)
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
dt = datetime(dt.year, dt.month, dt.day)
year_end = self.get_year_end(dt)
@@ -2411,7 +2312,7 @@ def year_has_extra_week(self, dt: datetime) -> bool:
return weeks_in_year == 53
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
if self._offset.is_on_offset(dt):
return True
@@ -2482,7 +2383,7 @@ def apply(self, other):
return new
def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not _is_normalized(dt):
+ if self.normalize and not is_normalized(dt):
return False
return date(dt.year, dt.month, dt.day) == easter(dt.year)
| xref #32942, #33394 | https://api.github.com/repos/pandas-dev/pandas/pulls/33936 | 2020-05-02T02:18:07Z | 2020-05-02T17:25:32Z | 2020-05-02T17:25:32Z | 2020-05-02T17:58:49Z |
TYP: annotations in nanops | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 8dd46edb5579d..bab9df0b70598 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -8,7 +8,7 @@
from pandas._config import get_option
from pandas._libs import NaT, Timedelta, Timestamp, iNaT, lib
-from pandas._typing import ArrayLike, Dtype, F, Scalar
+from pandas._typing import ArrayLike, Dtype, DtypeObj, F, Scalar
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import _int64_max, maybe_upcast_putmask
@@ -133,7 +133,7 @@ def f(
return f
-def _bn_ok_dtype(dtype: Dtype, name: str) -> bool:
+def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool:
# Bottleneck chokes on datetime64, PeriodDtype (or and EA)
if not is_object_dtype(dtype) and not needs_i8_conversion(dtype):
@@ -166,7 +166,7 @@ def _has_infs(result) -> bool:
def _get_fill_value(
- dtype: Dtype, fill_value: Optional[Scalar] = None, fill_value_typ=None
+ dtype: DtypeObj, fill_value: Optional[Scalar] = None, fill_value_typ=None
):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
@@ -270,9 +270,9 @@ def _get_values(
Potential copy of input value array
mask : Optional[ndarray[bool]]
Mask for values, if deemed necessary to compute
- dtype : dtype
+ dtype : np.dtype
dtype for values
- dtype_max : dtype
+ dtype_max : np.dtype
platform independent dtype
fill_value : Any
fill value used
@@ -312,20 +312,20 @@ def _get_values(
# return a platform independent precision dtype
dtype_max = dtype
if is_integer_dtype(dtype) or is_bool_dtype(dtype):
- dtype_max = np.int64
+ dtype_max = np.dtype(np.int64)
elif is_float_dtype(dtype):
- dtype_max = np.float64
+ dtype_max = np.dtype(np.float64)
return values, mask, dtype, dtype_max, fill_value
-def _na_ok_dtype(dtype) -> bool:
+def _na_ok_dtype(dtype: DtypeObj) -> bool:
if needs_i8_conversion(dtype):
return False
return not issubclass(dtype.type, np.integer)
-def _wrap_results(result, dtype: Dtype, fill_value=None):
+def _wrap_results(result, dtype: DtypeObj, fill_value=None):
""" wrap our results if needed """
if is_datetime64_any_dtype(dtype):
if fill_value is None:
@@ -597,7 +597,7 @@ def get_median(x):
return np.nan
return np.nanmedian(x[mask])
- values, mask, dtype, dtype_max, _ = _get_values(values, skipna, mask=mask)
+ values, mask, dtype, _, _ = _get_values(values, skipna, mask=mask)
if not is_float_dtype(values.dtype):
try:
values = values.astype("f8")
@@ -716,7 +716,7 @@ def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
1.0
"""
orig_dtype = values.dtype
- values, mask, dtype, dtype_max, fill_value = _get_values(values, skipna, mask=mask)
+ values, mask, _, _, _ = _get_values(values, skipna, mask=mask)
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask))
return _wrap_results(result, orig_dtype)
@@ -910,9 +910,7 @@ def nanargmax(
>>> nanops.nanargmax(arr, axis=1)
array([2, 2, 1, 1], dtype=int64)
"""
- values, mask, dtype, _, _ = _get_values(
- values, True, fill_value_typ="-inf", mask=mask
- )
+ values, mask, _, _, _ = _get_values(values, True, fill_value_typ="-inf", mask=mask)
result = values.argmax(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result
@@ -956,9 +954,7 @@ def nanargmin(
>>> nanops.nanargmin(arr, axis=1)
array([0, 0, 1, 1], dtype=int64)
"""
- values, mask, dtype, _, _ = _get_values(
- values, True, fill_value_typ="+inf", mask=mask
- )
+ values, mask, _, _, _ = _get_values(values, True, fill_value_typ="+inf", mask=mask)
result = values.argmin(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result
| tightening types a little bit.
Some of the other functions in this file have inaccurate return types, saving that for a separate pass | https://api.github.com/repos/pandas-dev/pandas/pulls/33935 | 2020-05-02T02:04:45Z | 2020-05-06T19:24:14Z | 2020-05-06T19:24:14Z | 2020-05-06T20:39:59Z |
PERF: Datetimelike lookups | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index d1f8957859337..832d09b062265 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -4,6 +4,7 @@
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
+from pandas.util._decorators import cache_readonly
from pandas.core.algorithms import take, unique
from pandas.core.arrays.base import ExtensionArray
@@ -64,6 +65,8 @@ def _validate_fill_value(self, fill_value):
# ------------------------------------------------------------------------
+ # TODO: make this a cache_readonly; for that to work we need to remove
+ # the _index_data kludge in libreduction
@property
def shape(self) -> Tuple[int, ...]:
return self._ndarray.shape
@@ -71,15 +74,15 @@ def shape(self) -> Tuple[int, ...]:
def __len__(self) -> int:
return self.shape[0]
- @property
+ @cache_readonly
def ndim(self) -> int:
return len(self.shape)
- @property
+ @cache_readonly
def size(self) -> int:
return np.prod(self.shape)
- @property
+ @cache_readonly
def nbytes(self) -> int:
return self._ndarray.nbytes
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index e07e2da164cac..257a51b423308 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -454,6 +454,8 @@ class DatetimeLikeArrayMixin(
# ------------------------------------------------------------------
# NDArrayBackedExtensionArray compat
+ # TODO: make this a cache_readonly; need to get around _index_data
+ # kludge in libreduction
@property
def _ndarray(self) -> np.ndarray:
# NB: A bunch of Interval tests fail if we use ._data
@@ -526,6 +528,13 @@ def __getitem__(self, key):
only handle list-likes, slices, and integer scalars
"""
+ if lib.is_integer(key):
+ # fast-path
+ result = self._data[key]
+ if self.ndim == 1:
+ return self._box_func(result)
+ return self._simple_new(result, dtype=self.dtype)
+
if com.is_bool_indexer(key):
# first convert to boolean, because check_array_indexer doesn't
# allow object dtype
| cc @TomAugspurger this should address at least some of the regressions you posted about this morning. | https://api.github.com/repos/pandas-dev/pandas/pulls/33933 | 2020-05-01T21:26:37Z | 2020-05-02T16:27:25Z | 2020-05-02T16:27:25Z | 2020-05-04T13:26:01Z |
TST: tighten xfails in test_strings | diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 35786ce64ac15..d9396d70f9112 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -209,19 +209,8 @@ def test_api_per_dtype(self, index_or_series, dtype, any_skipna_inferred_dtype):
box = index_or_series
inferred_dtype, values = any_skipna_inferred_dtype
- if dtype == "category" and len(values) and values[1] is pd.NA:
- pytest.xfail(reason="Categorical does not yet support pd.NA")
-
t = box(values, dtype=dtype) # explicit dtype to avoid casting
- # TODO: get rid of these xfails
- if dtype == "category" and inferred_dtype in ["period", "interval"]:
- pytest.xfail(
- reason="Conversion to numpy array fails because "
- "the ._values-attribute is not a numpy array for "
- "PeriodArray/IntervalArray; see GH 23553"
- )
-
types_passing_constructor = [
"string",
"unicode",
@@ -247,6 +236,7 @@ def test_api_per_method(
dtype,
any_allowed_skipna_inferred_dtype,
any_string_method,
+ request,
):
# this test does not check correctness of the different methods,
# just that the methods work on the specified (inferred) dtypes,
@@ -258,26 +248,24 @@ def test_api_per_method(
method_name, args, kwargs = any_string_method
# TODO: get rid of these xfails
- if (
- method_name in ["partition", "rpartition"]
- and box == Index
- and inferred_dtype == "empty"
- ):
- pytest.xfail(reason="Method cannot deal with empty Index")
- if (
- method_name == "split"
- and box == Index
- and values.size == 0
- and kwargs.get("expand", None) is not None
- ):
- pytest.xfail(reason="Split fails on empty Series when expand=True")
- if (
- method_name == "get_dummies"
- and box == Index
- and inferred_dtype == "empty"
- and (dtype == object or values.size == 0)
- ):
- pytest.xfail(reason="Need to fortify get_dummies corner cases")
+ reason = None
+ if box is Index and values.size == 0:
+ if method_name in ["partition", "rpartition"] and kwargs.get(
+ "expand", True
+ ):
+ reason = "Method cannot deal with empty Index"
+ elif method_name == "split" and kwargs.get("expand", None):
+ reason = "Split fails on empty Series when expand=True"
+ elif method_name == "get_dummies":
+ reason = "Need to fortify get_dummies corner cases"
+
+ elif box is Index and inferred_dtype == "empty" and dtype == object:
+ if method_name == "get_dummies":
+ reason = "Need to fortify get_dummies corner cases"
+
+ if reason is not None:
+ mark = pytest.mark.xfail(reason=reason)
+ request.node.add_marker(mark)
t = box(values, dtype=dtype) # explicit dtype to avoid casting
method = getattr(t.str, method_name)
| cc @TomAugspurger | https://api.github.com/repos/pandas-dev/pandas/pulls/33932 | 2020-05-01T21:16:35Z | 2020-05-02T15:29:54Z | 2020-05-02T15:29:54Z | 2020-05-02T16:21:19Z |
BUG: Fix small memory access errors in ujson objToJSON.c | diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index 0eae7a36a29c3..c71e941f7d6e8 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -1458,9 +1458,9 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,
if (is_datetimelike) {
if (nanosecVal == get_nat()) {
- len = 5; // TODO: shouldn't require extra space for terminator
- cLabel = PyObject_Malloc(len);
- strncpy(cLabel, "null", len);
+ len = 4;
+ cLabel = PyObject_Malloc(len + 1);
+ strncpy(cLabel, "null", len + 1);
} else {
if (enc->datetimeIso) {
if ((type_num == NPY_TIMEDELTA) || (PyDelta_Check(item))) {
@@ -1486,23 +1486,22 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,
}
}
} else { // Fallback to string representation
- PyObject *str = PyObject_Str(item);
- if (str == NULL) {
- Py_DECREF(item);
+ // Replace item with the string to keep it alive.
+ Py_SETREF(item, PyObject_Str(item));
+ if (item == NULL) {
NpyArr_freeLabels(ret, num);
ret = 0;
break;
}
- cLabel = (char *)PyUnicode_AsUTF8(str);
- Py_DECREF(str);
+ cLabel = (char *)PyUnicode_AsUTF8(item);
len = strlen(cLabel);
}
- Py_DECREF(item);
// Add 1 to include NULL terminator
ret[i] = PyObject_Malloc(len + 1);
memcpy(ret[i], cLabel, len + 1);
+ Py_DECREF(item);
if (is_datetimelike) {
PyObject_Free(cLabel);
| These were found (and validated fixed) using valgrind. It is likely
that none of these changes should create any issues (except maybe
on a debug build of python?). But silencing valgrind warnings is
good on its own, to ease possible future debugging using valgrind.
----
NOTE: I removed skipping of `test_astype_generic_timestamp_no_frequency`, this is just out of curiosity, I would be very surprised if it made a difference. So this should probably be only merged after undoing the test change.
- [ ] 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/33929 | 2020-05-01T19:42:04Z | 2020-05-02T16:34:44Z | 2020-05-02T16:34:44Z | 2020-05-02T16:34:48Z |
TST/REF: Move static methods out of consistency classes | diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py
index 37048265253f7..99f1842babc77 100644
--- a/pandas/tests/window/moments/test_moments_ewm.py
+++ b/pandas/tests/window/moments/test_moments_ewm.py
@@ -281,24 +281,26 @@ def setup_method(self, method):
def test_ewmcov_pairwise(self):
self._check_pairwise_moment("ewm", "cov", span=10, min_periods=5)
- @pytest.mark.parametrize("name", ["cov", "corr"])
- def test_ewm_corr_cov(self, name, min_periods, binary_ew_data):
- A, B = binary_ew_data
-
- check_binary_ew(name="corr", A=A, B=B)
- check_binary_ew_min_periods("corr", min_periods, A, B)
-
def test_ewmcorr_pairwise(self):
self._check_pairwise_moment("ewm", "corr", span=10, min_periods=5)
- @pytest.mark.parametrize("name", ["cov", "corr"])
- def test_different_input_array_raise_exception(self, name, binary_ew_data):
- A, _ = binary_ew_data
- msg = "Input arrays must be of the same type!"
- # exception raised is Exception
- with pytest.raises(Exception, match=msg):
- ew_func(A, randn(50), 20, name=name, min_periods=5)
+@pytest.mark.parametrize("name", ["cov", "corr"])
+def test_ewm_corr_cov(name, min_periods, binary_ew_data):
+ A, B = binary_ew_data
+
+ check_binary_ew(name="corr", A=A, B=B)
+ check_binary_ew_min_periods("corr", min_periods, A, B)
+
+
+@pytest.mark.parametrize("name", ["cov", "corr"])
+def test_different_input_array_raise_exception(name, binary_ew_data):
+
+ A, _ = binary_ew_data
+ msg = "Input arrays must be of the same type!"
+ # exception raised is Exception
+ with pytest.raises(Exception, match=msg):
+ ew_func(A, randn(50), 20, name=name, min_periods=5)
@pytest.mark.slow
diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py
index e97383823f00d..d20ab5131cf17 100644
--- a/pandas/tests/window/moments/test_moments_expanding.py
+++ b/pandas/tests/window/moments/test_moments_expanding.py
@@ -22,22 +22,6 @@ class TestExpandingMomentsConsistency(ConsistencyBase):
def setup_method(self, method):
self._create_data()
- def test_expanding_apply_args_kwargs(self, engine_and_raw):
- def mean_w_arg(x, const):
- return np.mean(x) + const
-
- engine, raw = engine_and_raw
-
- df = DataFrame(np.random.rand(20, 3))
-
- expected = df.expanding().apply(np.mean, engine=engine, raw=raw) + 20.0
-
- result = df.expanding().apply(mean_w_arg, engine=engine, raw=raw, args=(20,))
- tm.assert_frame_equal(result, expected)
-
- result = df.expanding().apply(mean_w_arg, raw=raw, kwargs={"const": 20})
- tm.assert_frame_equal(result, expected)
-
def test_expanding_corr(self):
A = self.series.dropna()
B = (A + randn(len(A)))[:-5]
@@ -90,100 +74,6 @@ def test_expanding_corr_pairwise(self):
).corr()
tm.assert_frame_equal(result, rolling_result)
- def test_expanding_cov_diff_index(self):
- # GH 7512
- s1 = Series([1, 2, 3], index=[0, 1, 2])
- s2 = Series([1, 3], index=[0, 2])
- result = s1.expanding().cov(s2)
- expected = Series([None, None, 2.0])
- tm.assert_series_equal(result, expected)
-
- s2a = Series([1, None, 3], index=[0, 1, 2])
- result = s1.expanding().cov(s2a)
- tm.assert_series_equal(result, expected)
-
- s1 = Series([7, 8, 10], index=[0, 1, 3])
- s2 = Series([7, 9, 10], index=[0, 2, 3])
- result = s1.expanding().cov(s2)
- expected = Series([None, None, None, 4.5])
- tm.assert_series_equal(result, expected)
-
- def test_expanding_corr_diff_index(self):
- # GH 7512
- s1 = Series([1, 2, 3], index=[0, 1, 2])
- s2 = Series([1, 3], index=[0, 2])
- result = s1.expanding().corr(s2)
- expected = Series([None, None, 1.0])
- tm.assert_series_equal(result, expected)
-
- s2a = Series([1, None, 3], index=[0, 1, 2])
- result = s1.expanding().corr(s2a)
- tm.assert_series_equal(result, expected)
-
- s1 = Series([7, 8, 10], index=[0, 1, 3])
- s2 = Series([7, 9, 10], index=[0, 2, 3])
- result = s1.expanding().corr(s2)
- expected = Series([None, None, None, 1.0])
- tm.assert_series_equal(result, expected)
-
- def test_expanding_cov_pairwise_diff_length(self):
- # GH 7512
- df1 = DataFrame([[1, 5], [3, 2], [3, 9]], columns=Index(["A", "B"], name="foo"))
- df1a = DataFrame(
- [[1, 5], [3, 9]], index=[0, 2], columns=Index(["A", "B"], name="foo")
- )
- df2 = DataFrame(
- [[5, 6], [None, None], [2, 1]], columns=Index(["X", "Y"], name="foo")
- )
- df2a = DataFrame(
- [[5, 6], [2, 1]], index=[0, 2], columns=Index(["X", "Y"], name="foo")
- )
- # TODO: xref gh-15826
- # .loc is not preserving the names
- result1 = df1.expanding().cov(df2, pairwise=True).loc[2]
- result2 = df1.expanding().cov(df2a, pairwise=True).loc[2]
- result3 = df1a.expanding().cov(df2, pairwise=True).loc[2]
- result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2]
- expected = DataFrame(
- [[-3.0, -6.0], [-5.0, -10.0]],
- columns=Index(["A", "B"], name="foo"),
- index=Index(["X", "Y"], name="foo"),
- )
- tm.assert_frame_equal(result1, expected)
- tm.assert_frame_equal(result2, expected)
- tm.assert_frame_equal(result3, expected)
- tm.assert_frame_equal(result4, expected)
-
- def test_expanding_corr_pairwise_diff_length(self):
- # GH 7512
- df1 = DataFrame(
- [[1, 2], [3, 2], [3, 4]],
- columns=["A", "B"],
- index=Index(range(3), name="bar"),
- )
- df1a = DataFrame(
- [[1, 2], [3, 4]], index=Index([0, 2], name="bar"), columns=["A", "B"]
- )
- df2 = DataFrame(
- [[5, 6], [None, None], [2, 1]],
- columns=["X", "Y"],
- index=Index(range(3), name="bar"),
- )
- df2a = DataFrame(
- [[5, 6], [2, 1]], index=Index([0, 2], name="bar"), columns=["X", "Y"]
- )
- result1 = df1.expanding().corr(df2, pairwise=True).loc[2]
- result2 = df1.expanding().corr(df2a, pairwise=True).loc[2]
- result3 = df1a.expanding().corr(df2, pairwise=True).loc[2]
- result4 = df1a.expanding().corr(df2a, pairwise=True).loc[2]
- expected = DataFrame(
- [[-1.0, -1.0], [-1.0, -1.0]], columns=["A", "B"], index=Index(["X", "Y"])
- )
- tm.assert_frame_equal(result1, expected)
- tm.assert_frame_equal(result2, expected)
- tm.assert_frame_equal(result3, expected)
- tm.assert_frame_equal(result4, expected)
-
@pytest.mark.parametrize("has_min_periods", [True, False])
@pytest.mark.parametrize(
"func,static_comp",
@@ -216,23 +106,6 @@ def expanding_mean(x, min_periods=1):
self._check_expanding(expanding_mean, np.mean, preserve_nan=False)
self._check_expanding_has_min_periods(expanding_mean, np.mean, has_min_periods)
- def test_expanding_apply_empty_series(self, engine_and_raw):
- engine, raw = engine_and_raw
- ser = Series([], dtype=np.float64)
- tm.assert_series_equal(
- ser, ser.expanding().apply(lambda x: x.mean(), raw=raw, engine=engine)
- )
-
- def test_expanding_apply_min_periods_0(self, engine_and_raw):
- # GH 8080
- engine, raw = engine_and_raw
- s = Series([None, None, None])
- result = s.expanding(min_periods=0).apply(
- lambda x: len(x), raw=raw, engine=engine
- )
- expected = Series([1.0, 2.0, 3.0])
- tm.assert_series_equal(result, expected)
-
def _check_expanding(self, func, static_comp, preserve_nan=True):
series_result = func(self.series)
@@ -272,115 +145,6 @@ def _check_expanding_has_min_periods(self, func, static_comp, has_min_periods):
result = func(ser)
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
- @pytest.mark.parametrize(
- "f",
- [
- lambda x: x.expanding().count(),
- lambda x: x.expanding(min_periods=5).cov(x, pairwise=False),
- lambda x: x.expanding(min_periods=5).corr(x, pairwise=False),
- lambda x: x.expanding(min_periods=5).max(),
- lambda x: x.expanding(min_periods=5).min(),
- lambda x: x.expanding(min_periods=5).sum(),
- lambda x: x.expanding(min_periods=5).mean(),
- lambda x: x.expanding(min_periods=5).std(),
- lambda x: x.expanding(min_periods=5).var(),
- lambda x: x.expanding(min_periods=5).skew(),
- lambda x: x.expanding(min_periods=5).kurt(),
- lambda x: x.expanding(min_periods=5).quantile(0.5),
- lambda x: x.expanding(min_periods=5).median(),
- lambda x: x.expanding(min_periods=5).apply(sum, raw=False),
- lambda x: x.expanding(min_periods=5).apply(sum, raw=True),
- ],
- )
- def test_moment_functions_zero_length(self, f):
- # GH 8056
- s = Series(dtype=np.float64)
- s_expected = s
- df1 = DataFrame()
- df1_expected = df1
- df2 = DataFrame(columns=["a"])
- df2["a"] = df2["a"].astype("float64")
- df2_expected = df2
-
- s_result = f(s)
- tm.assert_series_equal(s_result, s_expected)
-
- df1_result = f(df1)
- tm.assert_frame_equal(df1_result, df1_expected)
-
- df2_result = f(df2)
- tm.assert_frame_equal(df2_result, df2_expected)
-
- @pytest.mark.parametrize(
- "f",
- [
- lambda x: (x.expanding(min_periods=5).cov(x, pairwise=True)),
- lambda x: (x.expanding(min_periods=5).corr(x, pairwise=True)),
- ],
- )
- def test_moment_functions_zero_length_pairwise(self, f):
-
- df1 = DataFrame()
- df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar"))
- df2["a"] = df2["a"].astype("float64")
-
- df1_expected = DataFrame(
- index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([])
- )
- df2_expected = DataFrame(
- index=MultiIndex.from_product(
- [df2.index, df2.columns], names=["bar", "foo"]
- ),
- columns=Index(["a"], name="foo"),
- dtype="float64",
- )
-
- df1_result = f(df1)
- tm.assert_frame_equal(df1_result, df1_expected)
-
- df2_result = f(df2)
- tm.assert_frame_equal(df2_result, df2_expected)
-
- @pytest.mark.slow
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_consistency(self, consistency_data, min_periods):
- x, is_constant, no_nans = consistency_data
- # suppress warnings about empty slices, as we are deliberately testing
- # with empty/0-length Series/DataFrames
- with warnings.catch_warnings():
- warnings.filterwarnings(
- "ignore",
- message=".*(empty slice|0 for slice).*",
- category=RuntimeWarning,
- )
-
- # test consistency between different expanding_* moments
- moments_consistency_mock_mean(
- x=x,
- mean=lambda x: x.expanding(min_periods=min_periods).mean(),
- mock_mean=lambda x: x.expanding(min_periods=min_periods).sum()
- / x.expanding().count(),
- )
-
- moments_consistency_is_constant(
- x=x,
- is_constant=is_constant,
- min_periods=min_periods,
- count=lambda x: x.expanding().count(),
- mean=lambda x: x.expanding(min_periods=min_periods).mean(),
- corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
- )
-
- moments_consistency_var_debiasing_factors(
- x=x,
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- var_debiasing_factors=lambda x: (
- x.expanding().count()
- / (x.expanding().count() - 1.0).replace(0.0, np.nan)
- ),
- )
-
@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
def test_expanding_apply_consistency(self, consistency_data, min_periods):
x, is_constant, no_nans = consistency_data
@@ -479,3 +243,241 @@ def test_expanding_consistency_series(consistency_data, min_periods):
std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_expanding_consistency(consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
+ # suppress warnings about empty slices, as we are deliberately testing
+ # with empty/0-length Series/DataFrames
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
+ )
+
+ # test consistency between different expanding_* moments
+ moments_consistency_mock_mean(
+ x=x,
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ mock_mean=lambda x: x.expanding(min_periods=min_periods).sum()
+ / x.expanding().count(),
+ )
+
+ moments_consistency_is_constant(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: x.expanding().count(),
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
+ )
+
+ moments_consistency_var_debiasing_factors(
+ x=x,
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ var_debiasing_factors=lambda x: (
+ x.expanding().count()
+ / (x.expanding().count() - 1.0).replace(0.0, np.nan)
+ ),
+ )
+
+
+@pytest.mark.parametrize(
+ "f",
+ [
+ lambda x: (x.expanding(min_periods=5).cov(x, pairwise=True)),
+ lambda x: (x.expanding(min_periods=5).corr(x, pairwise=True)),
+ ],
+)
+def test_moment_functions_zero_length_pairwise(f):
+
+ df1 = DataFrame()
+ df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar"))
+ df2["a"] = df2["a"].astype("float64")
+
+ df1_expected = DataFrame(
+ index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([])
+ )
+ df2_expected = DataFrame(
+ index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]),
+ columns=Index(["a"], name="foo"),
+ dtype="float64",
+ )
+
+ df1_result = f(df1)
+ tm.assert_frame_equal(df1_result, df1_expected)
+
+ df2_result = f(df2)
+ tm.assert_frame_equal(df2_result, df2_expected)
+
+
+@pytest.mark.parametrize(
+ "f",
+ [
+ lambda x: x.expanding().count(),
+ lambda x: x.expanding(min_periods=5).cov(x, pairwise=False),
+ lambda x: x.expanding(min_periods=5).corr(x, pairwise=False),
+ lambda x: x.expanding(min_periods=5).max(),
+ lambda x: x.expanding(min_periods=5).min(),
+ lambda x: x.expanding(min_periods=5).sum(),
+ lambda x: x.expanding(min_periods=5).mean(),
+ lambda x: x.expanding(min_periods=5).std(),
+ lambda x: x.expanding(min_periods=5).var(),
+ lambda x: x.expanding(min_periods=5).skew(),
+ lambda x: x.expanding(min_periods=5).kurt(),
+ lambda x: x.expanding(min_periods=5).quantile(0.5),
+ lambda x: x.expanding(min_periods=5).median(),
+ lambda x: x.expanding(min_periods=5).apply(sum, raw=False),
+ lambda x: x.expanding(min_periods=5).apply(sum, raw=True),
+ ],
+)
+def test_moment_functions_zero_length(f):
+ # GH 8056
+ s = Series(dtype=np.float64)
+ s_expected = s
+ df1 = DataFrame()
+ df1_expected = df1
+ df2 = DataFrame(columns=["a"])
+ df2["a"] = df2["a"].astype("float64")
+ df2_expected = df2
+
+ s_result = f(s)
+ tm.assert_series_equal(s_result, s_expected)
+
+ df1_result = f(df1)
+ tm.assert_frame_equal(df1_result, df1_expected)
+
+ df2_result = f(df2)
+ tm.assert_frame_equal(df2_result, df2_expected)
+
+
+def test_expanding_apply_empty_series(engine_and_raw):
+ engine, raw = engine_and_raw
+ ser = Series([], dtype=np.float64)
+ tm.assert_series_equal(
+ ser, ser.expanding().apply(lambda x: x.mean(), raw=raw, engine=engine)
+ )
+
+
+def test_expanding_apply_min_periods_0(engine_and_raw):
+ # GH 8080
+ engine, raw = engine_and_raw
+ s = Series([None, None, None])
+ result = s.expanding(min_periods=0).apply(lambda x: len(x), raw=raw, engine=engine)
+ expected = Series([1.0, 2.0, 3.0])
+ tm.assert_series_equal(result, expected)
+
+
+def test_expanding_cov_diff_index():
+ # GH 7512
+ s1 = Series([1, 2, 3], index=[0, 1, 2])
+ s2 = Series([1, 3], index=[0, 2])
+ result = s1.expanding().cov(s2)
+ expected = Series([None, None, 2.0])
+ tm.assert_series_equal(result, expected)
+
+ s2a = Series([1, None, 3], index=[0, 1, 2])
+ result = s1.expanding().cov(s2a)
+ tm.assert_series_equal(result, expected)
+
+ s1 = Series([7, 8, 10], index=[0, 1, 3])
+ s2 = Series([7, 9, 10], index=[0, 2, 3])
+ result = s1.expanding().cov(s2)
+ expected = Series([None, None, None, 4.5])
+ tm.assert_series_equal(result, expected)
+
+
+def test_expanding_corr_diff_index():
+ # GH 7512
+ s1 = Series([1, 2, 3], index=[0, 1, 2])
+ s2 = Series([1, 3], index=[0, 2])
+ result = s1.expanding().corr(s2)
+ expected = Series([None, None, 1.0])
+ tm.assert_series_equal(result, expected)
+
+ s2a = Series([1, None, 3], index=[0, 1, 2])
+ result = s1.expanding().corr(s2a)
+ tm.assert_series_equal(result, expected)
+
+ s1 = Series([7, 8, 10], index=[0, 1, 3])
+ s2 = Series([7, 9, 10], index=[0, 2, 3])
+ result = s1.expanding().corr(s2)
+ expected = Series([None, None, None, 1.0])
+ tm.assert_series_equal(result, expected)
+
+
+def test_expanding_cov_pairwise_diff_length():
+ # GH 7512
+ df1 = DataFrame([[1, 5], [3, 2], [3, 9]], columns=Index(["A", "B"], name="foo"))
+ df1a = DataFrame(
+ [[1, 5], [3, 9]], index=[0, 2], columns=Index(["A", "B"], name="foo")
+ )
+ df2 = DataFrame(
+ [[5, 6], [None, None], [2, 1]], columns=Index(["X", "Y"], name="foo")
+ )
+ df2a = DataFrame(
+ [[5, 6], [2, 1]], index=[0, 2], columns=Index(["X", "Y"], name="foo")
+ )
+ # TODO: xref gh-15826
+ # .loc is not preserving the names
+ result1 = df1.expanding().cov(df2, pairwise=True).loc[2]
+ result2 = df1.expanding().cov(df2a, pairwise=True).loc[2]
+ result3 = df1a.expanding().cov(df2, pairwise=True).loc[2]
+ result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2]
+ expected = DataFrame(
+ [[-3.0, -6.0], [-5.0, -10.0]],
+ columns=Index(["A", "B"], name="foo"),
+ index=Index(["X", "Y"], name="foo"),
+ )
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+ tm.assert_frame_equal(result3, expected)
+ tm.assert_frame_equal(result4, expected)
+
+
+def test_expanding_corr_pairwise_diff_length():
+ # GH 7512
+ df1 = DataFrame(
+ [[1, 2], [3, 2], [3, 4]], columns=["A", "B"], index=Index(range(3), name="bar"),
+ )
+ df1a = DataFrame(
+ [[1, 2], [3, 4]], index=Index([0, 2], name="bar"), columns=["A", "B"]
+ )
+ df2 = DataFrame(
+ [[5, 6], [None, None], [2, 1]],
+ columns=["X", "Y"],
+ index=Index(range(3), name="bar"),
+ )
+ df2a = DataFrame(
+ [[5, 6], [2, 1]], index=Index([0, 2], name="bar"), columns=["X", "Y"]
+ )
+ result1 = df1.expanding().corr(df2, pairwise=True).loc[2]
+ result2 = df1.expanding().corr(df2a, pairwise=True).loc[2]
+ result3 = df1a.expanding().corr(df2, pairwise=True).loc[2]
+ result4 = df1a.expanding().corr(df2a, pairwise=True).loc[2]
+ expected = DataFrame(
+ [[-1.0, -1.0], [-1.0, -1.0]], columns=["A", "B"], index=Index(["X", "Y"])
+ )
+ tm.assert_frame_equal(result1, expected)
+ tm.assert_frame_equal(result2, expected)
+ tm.assert_frame_equal(result3, expected)
+ tm.assert_frame_equal(result4, expected)
+
+
+def test_expanding_apply_args_kwargs(engine_and_raw):
+ def mean_w_arg(x, const):
+ return np.mean(x) + const
+
+ engine, raw = engine_and_raw
+
+ df = DataFrame(np.random.rand(20, 3))
+
+ expected = df.expanding().apply(np.mean, engine=engine, raw=raw) + 20.0
+
+ result = df.expanding().apply(mean_w_arg, engine=engine, raw=raw, args=(20,))
+ tm.assert_frame_equal(result, expected)
+
+ result = df.expanding().apply(mean_w_arg, raw=raw, kwargs={"const": 20})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index c15b7ed00b9e3..c7d3a50ec13ae 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -1028,51 +1028,6 @@ def test_rolling_corr(self):
def test_rolling_corr_pairwise(self):
self._check_pairwise_moment("rolling", "corr", window=10, min_periods=5)
- @pytest.mark.parametrize("window", range(7))
- def test_rolling_corr_with_zero_variance(self, window):
- # GH 18430
- s = pd.Series(np.zeros(20))
- other = pd.Series(np.arange(20))
-
- assert s.rolling(window=window).corr(other=other).isna().all()
-
- def test_flex_binary_moment(self):
- # GH3155
- # don't blow the stack
- msg = (
- "arguments to moment function must be of type "
- "np.ndarray/Series/DataFrame"
- )
- with pytest.raises(TypeError, match=msg):
- _flex_binary_moment(5, 6, None)
-
- def test_corr_sanity(self):
- # GH 3155
- df = DataFrame(
- np.array(
- [
- [0.87024726, 0.18505595],
- [0.64355431, 0.3091617],
- [0.92372966, 0.50552513],
- [0.00203756, 0.04520709],
- [0.84780328, 0.33394331],
- [0.78369152, 0.63919667],
- ]
- )
- )
-
- res = df[0].rolling(5, center=True).corr(df[1])
- assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
-
- # and some fuzzing
- for _ in range(10):
- df = DataFrame(np.random.rand(30, 2))
- res = df[0].rolling(5, center=True).corr(df[1])
- try:
- assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
- except AssertionError:
- print(res)
-
@pytest.mark.parametrize("method", ["corr", "cov"])
def test_flex_binary_frame(self, method):
series = self.frame[1]
@@ -1096,338 +1051,384 @@ def test_flex_binary_frame(self, method):
)
tm.assert_frame_equal(res3, exp)
- def test_rolling_cov_diff_length(self):
- # GH 7512
- s1 = Series([1, 2, 3], index=[0, 1, 2])
- s2 = Series([1, 3], index=[0, 2])
- result = s1.rolling(window=3, min_periods=2).cov(s2)
- expected = Series([None, None, 2.0])
- tm.assert_series_equal(result, expected)
- s2a = Series([1, None, 3], index=[0, 1, 2])
- result = s1.rolling(window=3, min_periods=2).cov(s2a)
- tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("window", range(7))
+def test_rolling_corr_with_zero_variance(window):
+ # GH 18430
+ s = pd.Series(np.zeros(20))
+ other = pd.Series(np.arange(20))
- def test_rolling_corr_diff_length(self):
- # GH 7512
- s1 = Series([1, 2, 3], index=[0, 1, 2])
- s2 = Series([1, 3], index=[0, 2])
- result = s1.rolling(window=3, min_periods=2).corr(s2)
- expected = Series([None, None, 1.0])
- tm.assert_series_equal(result, expected)
+ assert s.rolling(window=window).corr(other=other).isna().all()
- s2a = Series([1, None, 3], index=[0, 1, 2])
- result = s1.rolling(window=3, min_periods=2).corr(s2a)
- tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize(
- "f",
- [
- lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False),
- lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False),
- lambda x: x.rolling(window=10, min_periods=5).max(),
- lambda x: x.rolling(window=10, min_periods=5).min(),
- lambda x: x.rolling(window=10, min_periods=5).sum(),
- lambda x: x.rolling(window=10, min_periods=5).mean(),
- lambda x: x.rolling(window=10, min_periods=5).std(),
- lambda x: x.rolling(window=10, min_periods=5).var(),
- lambda x: x.rolling(window=10, min_periods=5).skew(),
- lambda x: x.rolling(window=10, min_periods=5).kurt(),
- lambda x: x.rolling(window=10, min_periods=5).quantile(quantile=0.5),
- lambda x: x.rolling(window=10, min_periods=5).median(),
- lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False),
- lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True),
- lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(),
- ],
+def test_flex_binary_moment():
+ # GH3155
+ # don't blow the stack
+ msg = "arguments to moment function must be of type np.ndarray/Series/DataFrame"
+ with pytest.raises(TypeError, match=msg):
+ _flex_binary_moment(5, 6, None)
+
+
+def test_corr_sanity():
+ # GH 3155
+ df = DataFrame(
+ np.array(
+ [
+ [0.87024726, 0.18505595],
+ [0.64355431, 0.3091617],
+ [0.92372966, 0.50552513],
+ [0.00203756, 0.04520709],
+ [0.84780328, 0.33394331],
+ [0.78369152, 0.63919667],
+ ]
+ )
)
- @td.skip_if_no_scipy
- def test_rolling_functions_window_non_shrinkage(self, f):
- # GH 7764
- s = Series(range(4))
- s_expected = Series(np.nan, index=s.index)
- df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=["A", "B"])
- df_expected = DataFrame(np.nan, index=df.index, columns=df.columns)
- s_result = f(s)
- tm.assert_series_equal(s_result, s_expected)
+ res = df[0].rolling(5, center=True).corr(df[1])
+ assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
+ # and some fuzzing
+ for _ in range(10):
+ df = DataFrame(np.random.rand(30, 2))
+ res = df[0].rolling(5, center=True).corr(df[1])
+ try:
+ assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
+ except AssertionError:
+ print(res)
+
+
+def test_rolling_cov_diff_length():
+ # GH 7512
+ s1 = Series([1, 2, 3], index=[0, 1, 2])
+ s2 = Series([1, 3], index=[0, 2])
+ result = s1.rolling(window=3, min_periods=2).cov(s2)
+ expected = Series([None, None, 2.0])
+ tm.assert_series_equal(result, expected)
+
+ s2a = Series([1, None, 3], index=[0, 1, 2])
+ result = s1.rolling(window=3, min_periods=2).cov(s2a)
+ tm.assert_series_equal(result, expected)
+
+
+def test_rolling_corr_diff_length():
+ # GH 7512
+ s1 = Series([1, 2, 3], index=[0, 1, 2])
+ s2 = Series([1, 3], index=[0, 2])
+ result = s1.rolling(window=3, min_periods=2).corr(s2)
+ expected = Series([None, None, 1.0])
+ tm.assert_series_equal(result, expected)
+
+ s2a = Series([1, None, 3], index=[0, 1, 2])
+ result = s1.rolling(window=3, min_periods=2).corr(s2a)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "f",
+ [
+ lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False),
+ lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False),
+ lambda x: x.rolling(window=10, min_periods=5).max(),
+ lambda x: x.rolling(window=10, min_periods=5).min(),
+ lambda x: x.rolling(window=10, min_periods=5).sum(),
+ lambda x: x.rolling(window=10, min_periods=5).mean(),
+ lambda x: x.rolling(window=10, min_periods=5).std(),
+ lambda x: x.rolling(window=10, min_periods=5).var(),
+ lambda x: x.rolling(window=10, min_periods=5).skew(),
+ lambda x: x.rolling(window=10, min_periods=5).kurt(),
+ lambda x: x.rolling(window=10, min_periods=5).quantile(quantile=0.5),
+ lambda x: x.rolling(window=10, min_periods=5).median(),
+ lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False),
+ lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True),
+ lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(),
+ ],
+)
+@td.skip_if_no_scipy
+def test_rolling_functions_window_non_shrinkage(f):
+ # GH 7764
+ s = Series(range(4))
+ s_expected = Series(np.nan, index=s.index)
+ df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=["A", "B"])
+ df_expected = DataFrame(np.nan, index=df.index, columns=df.columns)
+
+ s_result = f(s)
+ tm.assert_series_equal(s_result, s_expected)
+
+ df_result = f(df)
+ tm.assert_frame_equal(df_result, df_expected)
+
+
+def test_rolling_functions_window_non_shrinkage_binary():
+
+ # corr/cov return a MI DataFrame
+ df = DataFrame(
+ [[1, 5], [3, 2], [3, 9], [-1, 0]],
+ columns=Index(["A", "B"], name="foo"),
+ index=Index(range(4), name="bar"),
+ )
+ df_expected = DataFrame(
+ columns=Index(["A", "B"], name="foo"),
+ index=pd.MultiIndex.from_product([df.index, df.columns], names=["bar", "foo"]),
+ dtype="float64",
+ )
+ functions = [
+ lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)),
+ lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)),
+ ]
+ for f in functions:
df_result = f(df)
tm.assert_frame_equal(df_result, df_expected)
- def test_rolling_functions_window_non_shrinkage_binary(self):
- # corr/cov return a MI DataFrame
- df = DataFrame(
- [[1, 5], [3, 2], [3, 9], [-1, 0]],
- columns=Index(["A", "B"], name="foo"),
- index=Index(range(4), name="bar"),
- )
- df_expected = DataFrame(
- columns=Index(["A", "B"], name="foo"),
- index=pd.MultiIndex.from_product(
- [df.index, df.columns], names=["bar", "foo"]
- ),
- dtype="float64",
- )
- functions = [
- lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)),
- lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)),
- ]
- for f in functions:
- df_result = f(df)
- tm.assert_frame_equal(df_result, df_expected)
-
- def test_rolling_skew_edge_cases(self):
-
- all_nan = Series([np.NaN] * 5)
-
- # yields all NaN (0 variance)
- d = Series([1] * 5)
- x = d.rolling(window=5).skew()
- tm.assert_series_equal(all_nan, x)
-
- # yields all NaN (window too small)
- d = Series(np.random.randn(5))
- x = d.rolling(window=2).skew()
- tm.assert_series_equal(all_nan, x)
-
- # yields [NaN, NaN, NaN, 0.177994, 1.548824]
- d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401])
- expected = Series([np.NaN, np.NaN, np.NaN, 0.177994, 1.548824])
- x = d.rolling(window=4).skew()
- tm.assert_series_equal(expected, x)
-
- def test_rolling_kurt_edge_cases(self):
-
- all_nan = Series([np.NaN] * 5)
-
- # yields all NaN (0 variance)
- d = Series([1] * 5)
- x = d.rolling(window=5).kurt()
- tm.assert_series_equal(all_nan, x)
-
- # yields all NaN (window too small)
- d = Series(np.random.randn(5))
- x = d.rolling(window=3).kurt()
- tm.assert_series_equal(all_nan, x)
-
- # yields [NaN, NaN, NaN, 1.224307, 2.671499]
- d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401])
- expected = Series([np.NaN, np.NaN, np.NaN, 1.224307, 2.671499])
- x = d.rolling(window=4).kurt()
- tm.assert_series_equal(expected, x)
-
- def test_rolling_skew_eq_value_fperr(self):
- # #18804 all rolling skew for all equal values should return Nan
- a = Series([1.1] * 15).rolling(window=10).skew()
- assert np.isnan(a).all()
-
- def test_rolling_kurt_eq_value_fperr(self):
- # #18804 all rolling kurt for all equal values should return Nan
- a = Series([1.1] * 15).rolling(window=10).kurt()
- assert np.isnan(a).all()
-
- def test_rolling_max_gh6297(self):
- """Replicate result expected in GH #6297"""
- indices = [datetime(1975, 1, i) for i in range(1, 6)]
- # So that we can have 2 datapoints on one of the days
- indices.append(datetime(1975, 1, 3, 6, 0))
- series = Series(range(1, 7), index=indices)
- # Use floats instead of ints as values
- series = series.map(lambda x: float(x))
- # Sort chronologically
- series = series.sort_index()
+def test_rolling_skew_edge_cases():
- expected = Series(
- [1.0, 2.0, 6.0, 4.0, 5.0],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- x = series.resample("D").max().rolling(window=1).max()
- tm.assert_series_equal(expected, x)
-
- def test_rolling_max_resample(self):
-
- indices = [datetime(1975, 1, i) for i in range(1, 6)]
- # So that we can have 3 datapoints on last day (4, 10, and 20)
- indices.append(datetime(1975, 1, 5, 1))
- indices.append(datetime(1975, 1, 5, 2))
- series = Series(list(range(0, 5)) + [10, 20], index=indices)
- # Use floats instead of ints as values
- series = series.map(lambda x: float(x))
- # Sort chronologically
- series = series.sort_index()
-
- # Default how should be max
- expected = Series(
- [0.0, 1.0, 2.0, 3.0, 20.0],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- x = series.resample("D").max().rolling(window=1).max()
- tm.assert_series_equal(expected, x)
+ all_nan = Series([np.NaN] * 5)
- # Now specify median (10.0)
- expected = Series(
- [0.0, 1.0, 2.0, 3.0, 10.0],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- x = series.resample("D").median().rolling(window=1).max()
- tm.assert_series_equal(expected, x)
+ # yields all NaN (0 variance)
+ d = Series([1] * 5)
+ x = d.rolling(window=5).skew()
+ tm.assert_series_equal(all_nan, x)
- # Now specify mean (4+10+20)/3
- v = (4.0 + 10.0 + 20.0) / 3.0
- expected = Series(
- [0.0, 1.0, 2.0, 3.0, v],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- x = series.resample("D").mean().rolling(window=1).max()
- tm.assert_series_equal(expected, x)
-
- def test_rolling_min_resample(self):
-
- indices = [datetime(1975, 1, i) for i in range(1, 6)]
- # So that we can have 3 datapoints on last day (4, 10, and 20)
- indices.append(datetime(1975, 1, 5, 1))
- indices.append(datetime(1975, 1, 5, 2))
- series = Series(list(range(0, 5)) + [10, 20], index=indices)
- # Use floats instead of ints as values
- series = series.map(lambda x: float(x))
- # Sort chronologically
- series = series.sort_index()
-
- # Default how should be min
- expected = Series(
- [0.0, 1.0, 2.0, 3.0, 4.0],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- r = series.resample("D").min().rolling(window=1)
- tm.assert_series_equal(expected, r.min())
-
- def test_rolling_median_resample(self):
-
- indices = [datetime(1975, 1, i) for i in range(1, 6)]
- # So that we can have 3 datapoints on last day (4, 10, and 20)
- indices.append(datetime(1975, 1, 5, 1))
- indices.append(datetime(1975, 1, 5, 2))
- series = Series(list(range(0, 5)) + [10, 20], index=indices)
- # Use floats instead of ints as values
- series = series.map(lambda x: float(x))
- # Sort chronologically
- series = series.sort_index()
-
- # Default how should be median
- expected = Series(
- [0.0, 1.0, 2.0, 3.0, 10],
- index=DatetimeIndex(
- [datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"
- ),
- )
- x = series.resample("D").median().rolling(window=1).median()
- tm.assert_series_equal(expected, x)
+ # yields all NaN (window too small)
+ d = Series(np.random.randn(5))
+ x = d.rolling(window=2).skew()
+ tm.assert_series_equal(all_nan, x)
- def test_rolling_median_memory_error(self):
- # GH11722
- n = 20000
- Series(np.random.randn(n)).rolling(window=2, center=False).median()
- Series(np.random.randn(n)).rolling(window=2, center=False).median()
+ # yields [NaN, NaN, NaN, 0.177994, 1.548824]
+ d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401])
+ expected = Series([np.NaN, np.NaN, np.NaN, 0.177994, 1.548824])
+ x = d.rolling(window=4).skew()
+ tm.assert_series_equal(expected, x)
- def test_rolling_min_max_numeric_types(self):
- # GH12373
- types_test = [np.dtype(f"f{width}") for width in [4, 8]]
- types_test.extend(
- [np.dtype(f"{sign}{width}") for width in [1, 2, 4, 8] for sign in "ui"]
- )
- for data_type in types_test:
- # Just testing that these don't throw exceptions and that
- # the return type is float64. Other tests will cover quantitative
- # correctness
- result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).max()
- assert result.dtypes[0] == np.dtype("f8")
- result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).min()
- assert result.dtypes[0] == np.dtype("f8")
-
- def test_moment_functions_zero_length(self):
- # GH 8056
- s = Series(dtype=np.float64)
- s_expected = s
- df1 = DataFrame()
- df1_expected = df1
- df2 = DataFrame(columns=["a"])
- df2["a"] = df2["a"].astype("float64")
- df2_expected = df2
-
- functions = [
- lambda x: x.rolling(window=10).count(),
- lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False),
- lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False),
- lambda x: x.rolling(window=10, min_periods=5).max(),
- lambda x: x.rolling(window=10, min_periods=5).min(),
- lambda x: x.rolling(window=10, min_periods=5).sum(),
- lambda x: x.rolling(window=10, min_periods=5).mean(),
- lambda x: x.rolling(window=10, min_periods=5).std(),
- lambda x: x.rolling(window=10, min_periods=5).var(),
- lambda x: x.rolling(window=10, min_periods=5).skew(),
- lambda x: x.rolling(window=10, min_periods=5).kurt(),
- lambda x: x.rolling(window=10, min_periods=5).quantile(0.5),
- lambda x: x.rolling(window=10, min_periods=5).median(),
- lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False),
- lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True),
- lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(),
- ]
- for f in functions:
- try:
- s_result = f(s)
- tm.assert_series_equal(s_result, s_expected)
-
- df1_result = f(df1)
- tm.assert_frame_equal(df1_result, df1_expected)
-
- df2_result = f(df2)
- tm.assert_frame_equal(df2_result, df2_expected)
- except (ImportError):
-
- # scipy needed for rolling_window
- continue
+def test_rolling_kurt_edge_cases():
- def test_moment_functions_zero_length_pairwise(self):
+ all_nan = Series([np.NaN] * 5)
- df1 = DataFrame()
- df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar"))
- df2["a"] = df2["a"].astype("float64")
+ # yields all NaN (0 variance)
+ d = Series([1] * 5)
+ x = d.rolling(window=5).kurt()
+ tm.assert_series_equal(all_nan, x)
+
+ # yields all NaN (window too small)
+ d = Series(np.random.randn(5))
+ x = d.rolling(window=3).kurt()
+ tm.assert_series_equal(all_nan, x)
+
+ # yields [NaN, NaN, NaN, 1.224307, 2.671499]
+ d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401])
+ expected = Series([np.NaN, np.NaN, np.NaN, 1.224307, 2.671499])
+ x = d.rolling(window=4).kurt()
+ tm.assert_series_equal(expected, x)
+
+
+def test_rolling_skew_eq_value_fperr():
+ # #18804 all rolling skew for all equal values should return Nan
+ a = Series([1.1] * 15).rolling(window=10).skew()
+ assert np.isnan(a).all()
+
+
+def test_rolling_kurt_eq_value_fperr():
+ # #18804 all rolling kurt for all equal values should return Nan
+ a = Series([1.1] * 15).rolling(window=10).kurt()
+ assert np.isnan(a).all()
- df1_expected = DataFrame(
- index=pd.MultiIndex.from_product([df1.index, df1.columns]),
- columns=Index([]),
- )
- df2_expected = DataFrame(
- index=pd.MultiIndex.from_product(
- [df2.index, df2.columns], names=["bar", "foo"]
- ),
- columns=Index(["a"], name="foo"),
- dtype="float64",
- )
- functions = [
- lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)),
- lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)),
- ]
+def test_rolling_max_gh6297():
+ """Replicate result expected in GH #6297"""
+ indices = [datetime(1975, 1, i) for i in range(1, 6)]
+ # So that we can have 2 datapoints on one of the days
+ indices.append(datetime(1975, 1, 3, 6, 0))
+ series = Series(range(1, 7), index=indices)
+ # Use floats instead of ints as values
+ series = series.map(lambda x: float(x))
+ # Sort chronologically
+ series = series.sort_index()
+
+ expected = Series(
+ [1.0, 2.0, 6.0, 4.0, 5.0],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ x = series.resample("D").max().rolling(window=1).max()
+ tm.assert_series_equal(expected, x)
+
+
+def test_rolling_max_resample():
+
+ indices = [datetime(1975, 1, i) for i in range(1, 6)]
+ # So that we can have 3 datapoints on last day (4, 10, and 20)
+ indices.append(datetime(1975, 1, 5, 1))
+ indices.append(datetime(1975, 1, 5, 2))
+ series = Series(list(range(0, 5)) + [10, 20], index=indices)
+ # Use floats instead of ints as values
+ series = series.map(lambda x: float(x))
+ # Sort chronologically
+ series = series.sort_index()
+
+ # Default how should be max
+ expected = Series(
+ [0.0, 1.0, 2.0, 3.0, 20.0],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ x = series.resample("D").max().rolling(window=1).max()
+ tm.assert_series_equal(expected, x)
+
+ # Now specify median (10.0)
+ expected = Series(
+ [0.0, 1.0, 2.0, 3.0, 10.0],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ x = series.resample("D").median().rolling(window=1).max()
+ tm.assert_series_equal(expected, x)
+
+ # Now specify mean (4+10+20)/3
+ v = (4.0 + 10.0 + 20.0) / 3.0
+ expected = Series(
+ [0.0, 1.0, 2.0, 3.0, v],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ x = series.resample("D").mean().rolling(window=1).max()
+ tm.assert_series_equal(expected, x)
+
+
+def test_rolling_min_resample():
+
+ indices = [datetime(1975, 1, i) for i in range(1, 6)]
+ # So that we can have 3 datapoints on last day (4, 10, and 20)
+ indices.append(datetime(1975, 1, 5, 1))
+ indices.append(datetime(1975, 1, 5, 2))
+ series = Series(list(range(0, 5)) + [10, 20], index=indices)
+ # Use floats instead of ints as values
+ series = series.map(lambda x: float(x))
+ # Sort chronologically
+ series = series.sort_index()
+
+ # Default how should be min
+ expected = Series(
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ r = series.resample("D").min().rolling(window=1)
+ tm.assert_series_equal(expected, r.min())
+
+
+def test_rolling_median_resample():
+
+ indices = [datetime(1975, 1, i) for i in range(1, 6)]
+ # So that we can have 3 datapoints on last day (4, 10, and 20)
+ indices.append(datetime(1975, 1, 5, 1))
+ indices.append(datetime(1975, 1, 5, 2))
+ series = Series(list(range(0, 5)) + [10, 20], index=indices)
+ # Use floats instead of ints as values
+ series = series.map(lambda x: float(x))
+ # Sort chronologically
+ series = series.sort_index()
+
+ # Default how should be median
+ expected = Series(
+ [0.0, 1.0, 2.0, 3.0, 10],
+ index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"),
+ )
+ x = series.resample("D").median().rolling(window=1).median()
+ tm.assert_series_equal(expected, x)
+
+
+def test_rolling_median_memory_error():
+ # GH11722
+ n = 20000
+ Series(np.random.randn(n)).rolling(window=2, center=False).median()
+ Series(np.random.randn(n)).rolling(window=2, center=False).median()
+
+
+def test_rolling_min_max_numeric_types():
+
+ # GH12373
+ types_test = [np.dtype(f"f{width}") for width in [4, 8]]
+ types_test.extend(
+ [np.dtype(f"{sign}{width}") for width in [1, 2, 4, 8] for sign in "ui"]
+ )
+ for data_type in types_test:
+ # Just testing that these don't throw exceptions and that
+ # the return type is float64. Other tests will cover quantitative
+ # correctness
+ result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).max()
+ assert result.dtypes[0] == np.dtype("f8")
+ result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).min()
+ assert result.dtypes[0] == np.dtype("f8")
+
+
+def test_moment_functions_zero_length():
+ # GH 8056
+ s = Series(dtype=np.float64)
+ s_expected = s
+ df1 = DataFrame()
+ df1_expected = df1
+ df2 = DataFrame(columns=["a"])
+ df2["a"] = df2["a"].astype("float64")
+ df2_expected = df2
+
+ functions = [
+ lambda x: x.rolling(window=10).count(),
+ lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False),
+ lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False),
+ lambda x: x.rolling(window=10, min_periods=5).max(),
+ lambda x: x.rolling(window=10, min_periods=5).min(),
+ lambda x: x.rolling(window=10, min_periods=5).sum(),
+ lambda x: x.rolling(window=10, min_periods=5).mean(),
+ lambda x: x.rolling(window=10, min_periods=5).std(),
+ lambda x: x.rolling(window=10, min_periods=5).var(),
+ lambda x: x.rolling(window=10, min_periods=5).skew(),
+ lambda x: x.rolling(window=10, min_periods=5).kurt(),
+ lambda x: x.rolling(window=10, min_periods=5).quantile(0.5),
+ lambda x: x.rolling(window=10, min_periods=5).median(),
+ lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False),
+ lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True),
+ lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(),
+ ]
+ for f in functions:
+ try:
+ s_result = f(s)
+ tm.assert_series_equal(s_result, s_expected)
- for f in functions:
df1_result = f(df1)
tm.assert_frame_equal(df1_result, df1_expected)
df2_result = f(df2)
tm.assert_frame_equal(df2_result, df2_expected)
+ except (ImportError):
+
+ # scipy needed for rolling_window
+ continue
+
+
+def test_moment_functions_zero_length_pairwise():
+
+ df1 = DataFrame()
+ df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar"))
+ df2["a"] = df2["a"].astype("float64")
+
+ df1_expected = DataFrame(
+ index=pd.MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]),
+ )
+ df2_expected = DataFrame(
+ index=pd.MultiIndex.from_product(
+ [df2.index, df2.columns], names=["bar", "foo"]
+ ),
+ columns=Index(["a"], name="foo"),
+ dtype="float64",
+ )
+
+ functions = [
+ lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)),
+ lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)),
+ ]
+
+ for f in functions:
+ df1_result = f(df1)
+ tm.assert_frame_equal(df1_result, df1_expected)
+
+ df2_result = f(df2)
+ tm.assert_frame_equal(df2_result, df2_expected)
@pytest.mark.parametrize(
| In order to keep such tests refactor PR more readable, in this PR, I only move those methods which are actually staticmethods out of huge consistency classes to be independent tests, so no code changes! And after this PR, the big consistency classes are broken down to much smaller.
This one will pave the way for replacing some other final fixtures & staticmethods out of classes
cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/33927 | 2020-05-01T17:53:19Z | 2020-05-02T15:33:14Z | 2020-05-02T15:33:14Z | 2020-05-02T15:33:19Z |
30999 fix bare pytest raises | diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py
index ad5a2de6eabac..19caf4eccf748 100644
--- a/pandas/tests/series/methods/test_asof.py
+++ b/pandas/tests/series/methods/test_asof.py
@@ -148,14 +148,14 @@ def test_errors(self):
# non-monotonic
assert not s.index.is_monotonic
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="requires a sorted index"):
s.asof(s.index[0])
# subset with Series
N = 10
rng = date_range("1/1/1990", periods=N, freq="53s")
s = Series(np.random.randn(N), index=rng)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="not valid for Series"):
s.asof(s.index[0], subset="foo")
def test_all_nans(self):
diff --git a/pandas/tests/series/methods/test_droplevel.py b/pandas/tests/series/methods/test_droplevel.py
index 435eb5751de4b..449ddd1cd0e49 100644
--- a/pandas/tests/series/methods/test_droplevel.py
+++ b/pandas/tests/series/methods/test_droplevel.py
@@ -15,5 +15,5 @@ def test_droplevel(self):
result = ser.droplevel("b", axis="index")
tm.assert_series_equal(result, expected)
# test that droplevel raises ValueError on axis != 0
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="No axis named columns"):
ser.droplevel(1, axis="columns")
diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py
index 44c55edf77c0a..532b8d16f0d5c 100644
--- a/pandas/tests/series/methods/test_tz_localize.py
+++ b/pandas/tests/series/methods/test_tz_localize.py
@@ -35,7 +35,7 @@ def test_series_tz_localize_ambiguous_bool(self):
expected0 = Series([expected0])
expected1 = Series([expected1])
- with pytest.raises(pytz.AmbiguousTimeError):
+ with tm.external_error_raised(pytz.AmbiguousTimeError):
ser.dt.tz_localize("US/Central")
result = ser.dt.tz_localize("US/Central", ambiguous=True)
@@ -66,10 +66,10 @@ def test_series_tz_localize_nonexistent(self, tz, method, exp):
dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min")
s = Series(1, dti)
if method == "raise":
- with pytest.raises(pytz.NonExistentTimeError):
+ with tm.external_error_raised(pytz.NonExistentTimeError):
s.tz_localize(tz, nonexistent=method)
elif exp == "invalid":
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="argument must be one of"):
dti.tz_localize(tz, nonexistent=method)
else:
result = s.tz_localize(tz, nonexistent=method)
diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py
index 0661828814888..54cf307a6ee66 100644
--- a/pandas/tests/series/test_apply.py
+++ b/pandas/tests/series/test_apply.py
@@ -248,18 +248,21 @@ def test_transform(self, string_series):
def test_transform_and_agg_error(self, string_series):
# we are trying to transform with an aggregator
- with pytest.raises(ValueError):
+ msg = "transforms cannot produce aggregated results"
+ with pytest.raises(ValueError, match=msg):
string_series.transform(["min", "max"])
- with pytest.raises(ValueError):
+ msg = "cannot combine transform and aggregation"
+ with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
string_series.agg(["sqrt", "max"])
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
string_series.transform(["sqrt", "max"])
- with pytest.raises(ValueError):
+ msg = "cannot perform both aggregation and transformation"
+ with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
string_series.agg({"foo": np.sqrt, "bar": "sum"})
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index c7a04843b8296..5c8a0d224c4f9 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -335,12 +335,13 @@ class TestSeriesComparison:
def test_comparison_different_length(self):
a = Series(["a", "b", "c"])
b = Series(["b", "a"])
- with pytest.raises(ValueError):
+ msg = "only compare identically-labeled Series"
+ with pytest.raises(ValueError, match=msg):
a < b
a = Series([1, 2])
b = Series([2, 3, 4])
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=msg):
a == b
@pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
@@ -474,23 +475,25 @@ def test_categorical_comparisons(self):
assert (~(f == a) == (f != a)).all()
# non-equality is not comparable
- with pytest.raises(TypeError):
+ msg = "can only compare equality or not"
+ with pytest.raises(TypeError, match=msg):
a < b
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
b < a
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
a > b
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
b > a
def test_unequal_categorical_comparison_raises_type_error(self):
# unequal comparison should raise for unordered cats
cat = Series(Categorical(list("abc")))
- with pytest.raises(TypeError):
+ msg = "can only compare equality or not"
+ with pytest.raises(TypeError, match=msg):
cat > "b"
cat = Series(Categorical(list("abc"), ordered=False))
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
cat > "b"
# https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057
@@ -498,13 +501,14 @@ def test_unequal_categorical_comparison_raises_type_error(self):
# for unequal comps, but not for equal/not equal
cat = Series(Categorical(list("abc"), ordered=True))
- with pytest.raises(TypeError):
+ msg = "Cannot compare a Categorical for op.+with a scalar"
+ with pytest.raises(TypeError, match=msg):
cat < "d"
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
cat > "d"
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
"d" < cat
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
"d" > cat
tm.assert_series_equal(cat == "d", Series([False, False, False]))
@@ -668,10 +672,11 @@ def test_series_add_aware_naive_raises(self):
ser_utc = ser.tz_localize("utc")
- with pytest.raises(Exception):
+ msg = "Cannot join tz-naive with tz-aware DatetimeIndex"
+ with pytest.raises(Exception, match=msg):
ser + ser_utc
- with pytest.raises(Exception):
+ with pytest.raises(Exception, match=msg):
ser_utc + ser
def test_datetime_understood(self):
diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py
index 0d7fd0529dc1f..8b1f58414e175 100644
--- a/pandas/tests/series/test_datetime_values.py
+++ b/pandas/tests/series/test_datetime_values.py
@@ -244,8 +244,9 @@ def get_dir(s):
s.dt.hour = 5
# trying to set a copy
+ msg = "modifications to a property of a datetimelike.+not supported"
with pd.option_context("chained_assignment", "raise"):
- with pytest.raises(com.SettingWithCopyError):
+ with pytest.raises(com.SettingWithCopyError, match=msg):
s.dt.hour[0] = 5
@pytest.mark.parametrize(
@@ -311,7 +312,7 @@ def test_dt_round_tz_ambiguous(self, method):
tm.assert_series_equal(result, expected)
# raise
- with pytest.raises(pytz.AmbiguousTimeError):
+ with tm.external_error_raised(pytz.AmbiguousTimeError):
getattr(df1.date.dt, method)("H", ambiguous="raise")
@pytest.mark.parametrize(
diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py
index ba1b3e9d0ca8e..e1c9682329271 100644
--- a/pandas/tests/series/test_operators.py
+++ b/pandas/tests/series/test_operators.py
@@ -121,23 +121,25 @@ def test_logical_operators_int_dtype_with_float(self):
# GH#9016: support bitwise op for integer types
s_0123 = Series(range(4), dtype="int64")
- with pytest.raises(TypeError):
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
s_0123 & np.NaN
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
s_0123 & 3.14
- with pytest.raises(TypeError):
+ msg = "unsupported operand type.+for &:"
+ with pytest.raises(TypeError, match=msg):
s_0123 & [0.1, 4, 3.14, 2]
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
s_0123 & np.array([0.1, 4, 3.14, 2])
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
s_0123 & Series([0.1, 4, -3.14, 2])
def test_logical_operators_int_dtype_with_str(self):
s_1111 = Series([1] * 4, dtype="int8")
-
- with pytest.raises(TypeError):
+ msg = "Cannot perform 'and_' with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
s_1111 & "a"
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match="unsupported operand.+for &"):
s_1111 & ["a", "b", "c", "d"]
def test_logical_operators_int_dtype_with_bool(self):
@@ -255,7 +257,8 @@ def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self):
def test_scalar_na_logical_ops_corners(self):
s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
- with pytest.raises(TypeError):
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
+ with pytest.raises(TypeError, match=msg):
s & datetime(2005, 1, 1)
s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)])
@@ -451,8 +454,9 @@ def test_logical_ops_label_based(self):
expected = Series([True, True, True], index=index)
tm.assert_series_equal(result, expected)
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
for v in [np.nan, "foo"]:
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
t | v
for v in [False, 0]:
@@ -469,8 +473,9 @@ def test_logical_ops_label_based(self):
result = Series([True, False, True], index=index) & v
expected = Series([False, False, False], index=index)
tm.assert_series_equal(result, expected)
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
for v in [np.nan]:
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
t & v
def test_logical_ops_df_compat(self):
diff --git a/pandas/tests/tools/test_to_time.py b/pandas/tests/tools/test_to_time.py
index 17ab492aca725..937570d89fb77 100644
--- a/pandas/tests/tools/test_to_time.py
+++ b/pandas/tests/tools/test_to_time.py
@@ -46,7 +46,8 @@ def test_parsers_time(self):
res = to_time(arg, format="%I:%M%p", errors="ignore")
tm.assert_numpy_array_equal(res, np.array(arg, dtype=np.object_))
- with pytest.raises(ValueError):
+ msg = "Cannot convert.+to a time with given format"
+ with pytest.raises(ValueError, match=msg):
to_time(arg, format="%I:%M%p", errors="raise")
tm.assert_series_equal(
| - [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/33925 | 2020-05-01T15:55:15Z | 2020-05-01T19:30:31Z | 2020-05-01T19:30:31Z | 2020-05-01T19:30:35Z |
API: make min/max on empty datetime df consistent with datetime serie… | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 9c424f70b1ee0..8dba9ff693d31 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -560,6 +560,7 @@ Datetimelike
- 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`)
- 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`
- Bug in :meth:`DatetimeIndex.intersection` and :meth:`TimedeltaIndex.intersection` with results not having the correct ``name`` attribute (:issue:`33904`)
- Bug in :meth:`DatetimeArray.__setitem__`, :meth:`TimedeltaArray.__setitem__`, :meth:`PeriodArray.__setitem__` incorrectly allowing values with ``int64`` dtype to be silently cast (:issue:`33717`)
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index bab9df0b70598..741ef64dbbf3b 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -384,8 +384,12 @@ def _na_for_min_count(
else:
assert axis is not None # assertion to make mypy happy
result_shape = values.shape[:axis] + values.shape[axis + 1 :]
- result = np.empty(result_shape, dtype=values.dtype)
- result.fill(fill_value)
+ # calling np.full with dtype parameter throws an ValueError when called
+ # with dtype=np.datetime64 and and fill_value=pd.NaT
+ try:
+ result = np.full(result_shape, fill_value, dtype=values.dtype)
+ except ValueError:
+ result = np.full(result_shape, fill_value)
return result
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index f69c85c070ca4..7869815c24037 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -1258,3 +1258,30 @@ def test_min_max_dt64_with_NaT(self):
res = df.max()
exp = pd.Series([pd.NaT], index=["foo"])
tm.assert_series_equal(res, exp)
+
+ def test_min_max_dt64_api_consistency_with_NaT(self):
+ # Calling the following sum functions returned an error for dataframes but
+ # returned NaT for series. These tests check that the API is consistent in
+ # min/max calls on empty Series/DataFrames. See GH:33704 for more
+ # information
+ df = pd.DataFrame(dict(x=pd.to_datetime([])))
+ expected_dt_series = pd.Series(pd.to_datetime([]))
+ # check axis 0
+ assert (df.min(axis=0).x is pd.NaT) == (expected_dt_series.min() is pd.NaT)
+ assert (df.max(axis=0).x is pd.NaT) == (expected_dt_series.max() is pd.NaT)
+
+ # check axis 1
+ tm.assert_series_equal(df.min(axis=1), expected_dt_series)
+ tm.assert_series_equal(df.max(axis=1), expected_dt_series)
+
+ def test_min_max_dt64_api_consistency_empty_df(self):
+ # check DataFrame/Series api consistency when calling min/max on an empty
+ # DataFrame/Series.
+ df = pd.DataFrame(dict(x=[]))
+ expected_float_series = pd.Series([], dtype=float)
+ # check axis 0
+ assert np.isnan(df.min(axis=0).x) == np.isnan(expected_float_series.min())
+ assert np.isnan(df.max(axis=0).x) == np.isnan(expected_float_series.max())
+ # check axis 1
+ tm.assert_series_equal(df.min(axis=1), expected_float_series)
+ tm.assert_series_equal(df.min(axis=1), expected_float_series)
| …s (#33704)
- [x] closes #33704
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Fixes the following issue:
```python
import pandas as pd
df = pd.DataFrame(dict(x=pd.to_datetime([])))
df.max()
```
throws a `ValueError` but
```python
pd.Series(pd.to_datetime([])).max()
```
results in `NaT`.
With this change, calling an DataFrame on en empty `pd.to_datetime([])`, results in
```
In[1]: df = pd.DataFrame(dict(x=pd.to_datetime([])))
In[2]: df.max()
Out[5]:
x NaT
dtype: datetime64[ns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/33911 | 2020-05-01T08:41:32Z | 2020-05-09T20:01:02Z | 2020-05-09T20:01:02Z | 2020-05-09T20:31:32Z |
REF: Create numba helper function for jitting + generating cache key | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 6745203d5beb7..c281fda71a7ec 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -77,11 +77,8 @@
from pandas.core.series import Series
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
- check_kwargs_and_nopython,
- get_jit_arguments,
- jit_user_function,
+ generate_numba_func,
split_for_numba,
- validate_udf,
)
from pandas.plotting import boxplot_frame_groupby
@@ -507,12 +504,8 @@ def _transform_general(
"""
if engine == "numba":
- nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
- check_kwargs_and_nopython(kwargs, nopython)
- validate_udf(func)
- cache_key = (func, "groupby_transform")
- numba_func = NUMBA_FUNC_CACHE.get(
- cache_key, jit_user_function(func, nopython, nogil, parallel)
+ numba_func, cache_key = generate_numba_func(
+ func, engine_kwargs, kwargs, "groupby_transform"
)
klass = type(self._selected_obj)
@@ -1407,12 +1400,8 @@ def _transform_general(
obj = self._obj_with_exclusions
gen = self.grouper.get_iterator(obj, axis=self.axis)
if engine == "numba":
- nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
- check_kwargs_and_nopython(kwargs, nopython)
- validate_udf(func)
- cache_key = (func, "groupby_transform")
- numba_func = NUMBA_FUNC_CACHE.get(
- cache_key, jit_user_function(func, nopython, nogil, parallel)
+ numba_func, cache_key = generate_numba_func(
+ func, engine_kwargs, kwargs, "groupby_transform"
)
else:
fast_path, slow_path = self._define_paths(func, *args, **kwargs)
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index f799baf354794..d67811988d0f8 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -56,11 +56,8 @@
)
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
- check_kwargs_and_nopython,
- get_jit_arguments,
- jit_user_function,
+ generate_numba_func,
split_for_numba,
- validate_udf,
)
@@ -689,12 +686,8 @@ def _aggregate_series_pure_python(
):
if engine == "numba":
- nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
- check_kwargs_and_nopython(kwargs, nopython)
- validate_udf(func)
- cache_key = (func, "groupby_agg")
- numba_func = NUMBA_FUNC_CACHE.get(
- cache_key, jit_user_function(func, nopython, nogil, parallel)
+ numba_func, cache_key = generate_numba_func(
+ func, engine_kwargs, kwargs, "groupby_agg"
)
group_index, _, ngroups = self.group_info
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py
index c2e4b38ad5b4d..c3f60ea7cc217 100644
--- a/pandas/core/util/numba_.py
+++ b/pandas/core/util/numba_.py
@@ -167,3 +167,43 @@ def f(values, index, ...):
f"The first {min_number_args} arguments to {func.__name__} must be "
f"{expected_args}"
)
+
+
+def generate_numba_func(
+ func: Callable,
+ engine_kwargs: Optional[Dict[str, bool]],
+ kwargs: dict,
+ cache_key_str: str,
+) -> Tuple[Callable, Tuple[Callable, str]]:
+ """
+ Return a JITed function and cache key for the NUMBA_FUNC_CACHE
+
+ This _may_ be specific to groupby (as it's only used there currently).
+
+ Parameters
+ ----------
+ func : function
+ user defined function
+ engine_kwargs : dict or None
+ numba.jit arguments
+ kwargs : dict
+ kwargs for func
+ cache_key_str : str
+ string representing the second part of the cache key tuple
+
+ Returns
+ -------
+ (JITed function, cache key)
+
+ Raises
+ ------
+ NumbaUtilError
+ """
+ nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
+ check_kwargs_and_nopython(kwargs, nopython)
+ validate_udf(func)
+ cache_key = (func, cache_key_str)
+ numba_func = NUMBA_FUNC_CACHE.get(
+ cache_key, jit_user_function(func, nopython, nogil, parallel)
+ )
+ return numba_func, cache_key
| - [x] xref https://github.com/pandas-dev/pandas/pull/33388#discussion_r413967963
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/33910 | 2020-05-01T05:38:10Z | 2020-05-01T19:32:24Z | 2020-05-01T19:32:24Z | 2020-05-01T20:32:41Z |
REF: de-duplicate listlike validation in DTA._validate_foo | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 25ac3e445822e..c0ac0a02d2a0c 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, TypeVar, Union, cast
+from typing import Any, Callable, Sequence, Type, TypeVar, Union, cast
import warnings
import numpy as np
@@ -10,7 +10,7 @@
from pandas._libs.tslibs.period import DIFFERENT_FREQ, IncompatibleFrequency, Period
from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds
from pandas._libs.tslibs.timestamps import RoundTo, round_nsint64
-from pandas._typing import DatetimeLikeScalar
+from pandas._typing import DatetimeLikeScalar, DtypeObj
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError, NullFrequencyError, PerformanceWarning
@@ -86,24 +86,10 @@ def _validate_comparison_value(self, other):
raise ValueError("Lengths must match")
else:
- if isinstance(other, list):
- # TODO: could use pd.Index to do inference?
- other = np.array(other)
-
- if not isinstance(other, (np.ndarray, type(self))):
- raise InvalidComparison(other)
-
- elif is_object_dtype(other.dtype):
- pass
-
- elif not type(self)._is_recognized_dtype(other.dtype):
- 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)
+ try:
+ other = self._validate_listlike(other, opname, allow_object=True)
+ except TypeError as err:
+ raise InvalidComparison(other) from err
return other
@@ -451,6 +437,8 @@ class DatetimeLikeArrayMixin(
_generate_range
"""
+ _is_recognized_dtype: Callable[[DtypeObj], bool]
+
# ------------------------------------------------------------------
# NDArrayBackedExtensionArray compat
@@ -761,6 +749,48 @@ def _validate_shift_value(self, fill_value):
return self._unbox(fill_value)
+ def _validate_listlike(
+ self,
+ value,
+ opname: str,
+ cast_str: bool = False,
+ cast_cat: bool = False,
+ allow_object: bool = False,
+ ):
+ if isinstance(value, type(self)):
+ return value
+
+ # Do type inference if necessary up front
+ # e.g. we passed PeriodIndex.values and got an ndarray of Periods
+ value = array(value)
+ value = extract_array(value, extract_numpy=True)
+
+ if cast_str and 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 cast_cat and is_categorical_dtype(value.dtype):
+ # e.g. we have a Categorical holding self.dtype
+ if is_dtype_equal(value.categories.dtype, self.dtype):
+ # TODO: do we need equal dtype or just comparable?
+ value = value._internal_get_values()
+
+ if allow_object and is_object_dtype(value.dtype):
+ pass
+
+ elif not type(self)._is_recognized_dtype(value.dtype):
+ raise TypeError(
+ f"{opname} requires compatible dtype or scalar, "
+ f"not {type(value).__name__}"
+ )
+
+ return value
+
def _validate_searchsorted_value(self, value):
if isinstance(value, str):
try:
@@ -776,41 +806,19 @@ 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)
-
- if not type(self)._is_recognized_dtype(value.dtype):
- raise TypeError(
- "searchsorted requires compatible dtype or scalar, "
- f"not {type(value).__name__}"
- )
+ elif not is_list_like(value):
+ raise TypeError(f"Unexpected type for 'value': {type(value)}")
else:
- raise TypeError(f"Unexpected type for 'value': {type(value)}")
+ # TODO: cast_str? we accept it for scalar
+ value = self._validate_listlike(value, "searchsorted")
return self._unbox(value)
def _validate_setitem_value(self, value):
if is_list_like(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.dtype):
- raise TypeError(
- "setitem requires compatible dtype or scalar, "
- f"not {type(value).__name__}"
- )
+ value = self._validate_listlike(value, "setitem", cast_str=True)
elif isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
@@ -851,18 +859,8 @@ def _validate_where_value(self, other):
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
- other = array(other)
- other = extract_array(other, extract_numpy=True)
-
- 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 type(self)._is_recognized_dtype(other.dtype):
- raise TypeError(f"Where requires matching dtype, not {other.dtype}")
+ other = self._validate_listlike(other, "where", cast_cat=True)
+ self._check_compatible_with(other, setitem=True)
self._check_compatible_with(other, setitem=True)
return self._unbox(other)
| Implements a helper `_validate_listlike` that is re-used across 4 of the _validate_foo methods. We can then smooth out the remaining differences by passing the same flags in each of the four usages. | https://api.github.com/repos/pandas-dev/pandas/pulls/33908 | 2020-05-01T03:05:05Z | 2020-05-06T23:05:57Z | 2020-05-06T23:05:57Z | 2020-05-07T01:31:47Z |
DEPR: get_value | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 7ad7e8f5a27b0..aa02c3bb9a1f8 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -487,6 +487,7 @@ Deprecations
arguments (:issue:`27573`).
- :func:`pandas.api.types.is_categorical` is deprecated and will be removed in a future version; use `:func:pandas.api.types.is_categorical_dtype` instead (:issue:`33385`)
+- :meth:`Index.get_value` is deprecated and will be removed in a future version (:issue:`19728`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 4254fafa8bb3a..4e74f3e58362b 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4541,6 +4541,13 @@ def get_value(self, series: "Series", key):
-------
scalar or Series
"""
+ warnings.warn(
+ "get_value is deprecated and will be removed in a future version. "
+ "Use Series[key] instead",
+ FutureWarning,
+ stacklevel=2,
+ )
+
self._check_indexing_error(key)
try:
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py
index d74b2bd03c0a0..097ee20534e4e 100644
--- a/pandas/tests/indexes/datetimes/test_indexing.py
+++ b/pandas/tests/indexes/datetimes/test_indexing.py
@@ -608,13 +608,17 @@ def test_get_value(self):
key = dti[1]
with pytest.raises(AttributeError, match="has no attribute '_values'"):
- dti.get_value(arr, key)
+ with tm.assert_produces_warning(FutureWarning):
+ dti.get_value(arr, key)
- result = dti.get_value(ser, key)
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti.get_value(ser, key)
assert result == 7
- result = dti.get_value(ser, key.to_pydatetime())
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti.get_value(ser, key.to_pydatetime())
assert result == 7
- result = dti.get_value(ser, key.to_datetime64())
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti.get_value(ser, key.to_datetime64())
assert result == 7
diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py
index 2779cd92fca00..eaba0bb3793b2 100644
--- a/pandas/tests/indexes/period/test_indexing.py
+++ b/pandas/tests/indexes/period/test_indexing.py
@@ -673,21 +673,24 @@ def test_get_value(self):
input0 = pd.Series(np.array([1, 2, 3]), index=idx0)
expected0 = 2
- result0 = idx0.get_value(input0, p1)
+ with tm.assert_produces_warning(FutureWarning):
+ result0 = idx0.get_value(input0, p1)
assert result0 == expected0
idx1 = PeriodIndex([p1, p1, p2])
input1 = pd.Series(np.array([1, 2, 3]), index=idx1)
expected1 = input1.iloc[[0, 1]]
- result1 = idx1.get_value(input1, p1)
+ with tm.assert_produces_warning(FutureWarning):
+ result1 = idx1.get_value(input1, p1)
tm.assert_series_equal(result1, expected1)
idx2 = PeriodIndex([p1, p2, p1])
input2 = pd.Series(np.array([1, 2, 3]), index=idx2)
expected2 = input2.iloc[[0, 2]]
- result2 = idx2.get_value(input2, p1)
+ with tm.assert_produces_warning(FutureWarning):
+ result2 = idx2.get_value(input2, p1)
tm.assert_series_equal(result2, expected2)
@pytest.mark.parametrize("freq", ["H", "D"])
@@ -700,7 +703,8 @@ def test_get_value_datetime_hourly(self, freq):
ts = dti[0]
assert pi.get_loc(ts) == 0
- assert pi.get_value(ser, ts) == 7
+ with tm.assert_produces_warning(FutureWarning):
+ assert pi.get_value(ser, ts) == 7
assert ser[ts] == 7
assert ser.loc[ts] == 7
@@ -709,14 +713,16 @@ def test_get_value_datetime_hourly(self, freq):
with pytest.raises(KeyError, match="2016-01-01 03:00"):
pi.get_loc(ts2)
with pytest.raises(KeyError, match="2016-01-01 03:00"):
- pi.get_value(ser, ts2)
+ with tm.assert_produces_warning(FutureWarning):
+ pi.get_value(ser, ts2)
with pytest.raises(KeyError, match="2016-01-01 03:00"):
ser[ts2]
with pytest.raises(KeyError, match="2016-01-01 03:00"):
ser.loc[ts2]
else:
assert pi.get_loc(ts2) == 0
- assert pi.get_value(ser, ts2) == 7
+ with tm.assert_produces_warning(FutureWarning):
+ assert pi.get_value(ser, ts2) == 7
assert ser[ts2] == 7
assert ser.loc[ts2] == 7
@@ -726,13 +732,15 @@ def test_get_value_integer(self):
pi = dti.to_period("D")
ser = pd.Series(range(3), index=pi)
with pytest.raises(IndexError, match=msg):
- pi.get_value(ser, 16801)
+ with tm.assert_produces_warning(FutureWarning):
+ pi.get_value(ser, 16801)
msg = "index 46 is out of bounds for axis 0 with size 3"
pi2 = dti.to_period("Y") # duplicates, ordinals are all 46
ser2 = pd.Series(range(3), index=pi2)
with pytest.raises(IndexError, match=msg):
- pi2.get_value(ser2, 46)
+ with tm.assert_produces_warning(FutureWarning):
+ pi2.get_value(ser2, 46)
class TestContains:
@@ -758,7 +766,8 @@ def test_contains(self):
with pytest.raises(KeyError, match=key):
idx0.get_loc(key)
with pytest.raises(KeyError, match=key):
- idx0.get_value(ser, key)
+ with tm.assert_produces_warning(FutureWarning):
+ idx0.get_value(ser, key)
assert "2017-09" in idx0
diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py
index aa99207261e4e..660c32d44a7aa 100644
--- a/pandas/tests/indexes/period/test_partial_slicing.py
+++ b/pandas/tests/indexes/period/test_partial_slicing.py
@@ -113,7 +113,8 @@ def test_partial_slice_doesnt_require_monotonicity(self):
expected = ser[indexer_2014]
- result = nidx.get_value(ser, "2014")
+ with tm.assert_produces_warning(FutureWarning):
+ result = nidx.get_value(ser, "2014")
tm.assert_series_equal(result, expected)
result = ser.loc["2014"]
@@ -131,7 +132,8 @@ def test_partial_slice_doesnt_require_monotonicity(self):
expected = ser[indexer_may2015]
- result = nidx.get_value(ser, "May 2015")
+ with tm.assert_produces_warning(FutureWarning):
+ result = nidx.get_value(ser, "May 2015")
tm.assert_series_equal(result, expected)
result = ser.loc["May 2015"]
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 7b42e9646918e..9f235dcdbb295 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1697,9 +1697,11 @@ def test_get_value(self, indices):
with pytest.raises(AttributeError, match="has no attribute '_values'"):
# Index.get_value requires a Series, not an ndarray
- indices.get_value(values, value)
+ with tm.assert_produces_warning(FutureWarning):
+ indices.get_value(values, value)
- result = indices.get_value(Series(values, index=values), value)
+ with tm.assert_produces_warning(FutureWarning):
+ result = indices.get_value(Series(values, index=values), value)
tm.assert_almost_equal(result, values[67])
@pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index 0965694e5b51d..081090731a9b4 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -254,9 +254,11 @@ def test_lookups_datetimelike_values(self, vals):
expected = vals[1]
- result = ser.index.get_value(ser, 4.0)
+ with tm.assert_produces_warning(FutureWarning):
+ result = ser.index.get_value(ser, 4.0)
assert isinstance(result, type(expected)) and result == expected
- result = ser.index.get_value(ser, 4)
+ with tm.assert_produces_warning(FutureWarning):
+ result = ser.index.get_value(ser, 4)
assert isinstance(result, type(expected)) and result == expected
result = ser[4.0]
diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py
index ed11af8ef68ad..538aa1d3a1164 100644
--- a/pandas/tests/indexing/multiindex/test_partial.py
+++ b/pandas/tests/indexing/multiindex/test_partial.py
@@ -151,7 +151,8 @@ def test_getitem_intkey_leading_level(
with pytest.raises(KeyError, match="14"):
ser[14]
with pytest.raises(KeyError, match="14"):
- mi.get_value(ser, 14)
+ with tm.assert_produces_warning(FutureWarning):
+ mi.get_value(ser, 14)
# ---------------------------------------------------------------------
# AMBIGUOUS CASES!
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 8fa28d7b854c8..737e21af9242f 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -550,7 +550,8 @@ def test_getitem_categorical_str():
tm.assert_series_equal(result, expected)
# Check the intermediate steps work as expected
- result = ser.index.get_value(ser, "a")
+ with tm.assert_produces_warning(FutureWarning):
+ result = ser.index.get_value(ser, "a")
tm.assert_series_equal(result, expected)
| - [x] closes #19728
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
No longer used internally. | https://api.github.com/repos/pandas-dev/pandas/pulls/33907 | 2020-05-01T02:20:09Z | 2020-05-01T12:54:54Z | 2020-05-01T12:54:54Z | 2020-05-01T14:30:44Z |
REF: implement _unbox to de-duplicate unwrapping | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 8b6ed002b3f47..fbaa4e36d14c1 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -8,7 +8,7 @@
from pandas._libs import NaT, NaTType, Timestamp, algos, iNaT, lib
from pandas._libs.tslibs.c_timestamp import integer_op_not_supported
from pandas._libs.tslibs.period import DIFFERENT_FREQ, IncompatibleFrequency, Period
-from pandas._libs.tslibs.timedeltas import Timedelta, delta_to_nanoseconds
+from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds
from pandas._libs.tslibs.timestamps import RoundTo, round_nsint64
from pandas._typing import DatetimeLikeScalar
from pandas.compat import set_function_name
@@ -52,6 +52,8 @@
from pandas.tseries import frequencies
from pandas.tseries.offsets import DateOffset, Tick
+DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
+
def _datetimelike_array_cmp(cls, op):
"""
@@ -122,12 +124,7 @@ def wrapper(self, other):
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
-
+ other_i8 = self._unbox(other)
result = op(self.asi8, other_i8)
o_mask = isna(other)
@@ -157,9 +154,7 @@ def _scalar_type(self) -> Type[DatetimeLikeScalar]:
"""
raise AbstractMethodError(self)
- def _scalar_from_string(
- self, value: str
- ) -> Union[Period, Timestamp, Timedelta, NaTType]:
+ def _scalar_from_string(self, value: str) -> DTScalarOrNaT:
"""
Construct a scalar type from a string.
@@ -179,13 +174,14 @@ def _scalar_from_string(
"""
raise AbstractMethodError(self)
- def _unbox_scalar(self, value: Union[Period, Timestamp, Timedelta, NaTType]) -> int:
+ def _unbox_scalar(self, value: DTScalarOrNaT) -> int:
"""
Unbox the integer value of a scalar `value`.
Parameters
----------
- value : Union[Period, Timestamp, Timedelta]
+ value : Period, Timestamp, Timedelta, or NaT
+ Depending on subclass.
Returns
-------
@@ -199,7 +195,7 @@ def _unbox_scalar(self, value: Union[Period, Timestamp, Timedelta, NaTType]) ->
raise AbstractMethodError(self)
def _check_compatible_with(
- self, other: Union[Period, Timestamp, Timedelta, NaTType], setitem: bool = False
+ self, other: DTScalarOrNaT, setitem: bool = False
) -> None:
"""
Verify that `self` and `other` are compatible.
@@ -727,17 +723,16 @@ def _validate_fill_value(self, fill_value):
ValueError
"""
if is_valid_nat_for_dtype(fill_value, self.dtype):
- fill_value = iNaT
+ fill_value = NaT
elif isinstance(fill_value, self._recognized_scalars):
- self._check_compatible_with(fill_value)
fill_value = self._scalar_type(fill_value)
- fill_value = self._unbox_scalar(fill_value)
else:
raise ValueError(
f"'fill_value' should be a {self._scalar_type}. "
f"Got '{str(fill_value)}'."
)
- return fill_value
+
+ return self._unbox(fill_value)
def _validate_shift_value(self, fill_value):
# TODO(2.0): once this deprecation is enforced, use _validate_fill_value
@@ -764,8 +759,7 @@ def _validate_shift_value(self, fill_value):
)
fill_value = new_fill
- fill_value = self._unbox_scalar(fill_value)
- return fill_value
+ return self._unbox(fill_value)
def _validate_searchsorted_value(self, value):
if isinstance(value, str):
@@ -797,13 +791,7 @@ def _validate_searchsorted_value(self, value):
else:
raise TypeError(f"Unexpected type for 'value': {type(value)}")
- if isinstance(value, type(self)):
- self._check_compatible_with(value)
- value = value.asi8
- else:
- value = self._unbox_scalar(value)
-
- return value
+ return self._unbox(value)
def _validate_setitem_value(self, value):
@@ -836,19 +824,11 @@ 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
+ return self._unbox(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
@@ -857,6 +837,9 @@ def _validate_insert_value(self, value):
f"cannot insert {type(self).__name__} with incompatible label"
)
+ self._check_compatible_with(value, setitem=True)
+ # TODO: if we dont have compat, should we raise or astype(object)?
+ # PeriodIndex does astype(object)
return value
def _validate_where_value(self, other):
@@ -864,7 +847,6 @@ def _validate_where_value(self, other):
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):
raise TypeError(f"Where requires matching dtype, not {type(other)}")
@@ -881,13 +863,20 @@ def _validate_where_value(self, other):
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)
+ self._check_compatible_with(other, setitem=True)
+ return self._unbox(other)
+
+ def _unbox(self, other) -> Union[np.int64, np.ndarray]:
+ """
+ Unbox either a scalar with _unbox_scalar or an instance of our own type.
+ """
if lib.is_scalar(other):
other = self._unbox_scalar(other)
else:
+ # same type as self
+ self._check_compatible_with(other)
other = other.view("i8")
-
return other
# ------------------------------------------------------------------
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index b7dfcd4cb188c..1460a2e762771 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -249,8 +249,7 @@ def _unbox_scalar(self, value: Union[Period, NaTType]) -> int:
if value is NaT:
return value.value
elif isinstance(value, self._scalar_type):
- if not isna(value):
- self._check_compatible_with(value)
+ self._check_compatible_with(value)
return value.ordinal
else:
raise ValueError(f"'value' should be a Period. Got '{value}' instead.")
| Ultimately we want these _validate_foo methods to be whittled down to only one or two methods. | https://api.github.com/repos/pandas-dev/pandas/pulls/33906 | 2020-04-30T23:35:27Z | 2020-05-01T19:34:23Z | 2020-05-01T19:34:23Z | 2020-05-01T20:16:19Z |
Fix #28552 Add test for DataFrame min/max preserve timezone | diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 7869815c24037..b4842e8d5e8ed 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -1285,3 +1285,16 @@ def test_min_max_dt64_api_consistency_empty_df(self):
# check axis 1
tm.assert_series_equal(df.min(axis=1), expected_float_series)
tm.assert_series_equal(df.min(axis=1), expected_float_series)
+
+ @pytest.mark.parametrize(
+ "initial",
+ ["2018-10-08 13:36:45+00:00", "2018-10-08 13:36:45+03:00"], # Non-UTC timezone
+ )
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_preserve_timezone(self, initial: str, method):
+ # GH 28552
+ initial_dt = pd.to_datetime(initial)
+ expected = Series([initial_dt])
+ df = DataFrame([expected])
+ result = getattr(df, method)(axis=1)
+ tm.assert_series_equal(result, expected)
| - [x] closes #28552
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry _(not applicable - no functionality added)_
Here's a test discussed in #28552. `mean` and other aggregates except for `min` and `max` are not covered since they don't support datetimes - it's a nan being returned.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33905 | 2020-04-30T21:15:40Z | 2020-05-12T13:32:09Z | 2020-05-12T13:32:09Z | 2020-05-12T17:04:20Z |
BUG: DTI/TDI intersection result names | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 40adeb28d47b6..2c8ad1782af4d 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -547,6 +547,7 @@ Datetimelike
- 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`)
- 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`)
+- Bug in :meth:`DatetimeIndex.intersection` and :meth:`TimedeltaIndex.intersection` with results not having the correct ``name`` attribute (:issue:`33904`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index fe48f05820a4a..3f18f69149658 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -6,7 +6,7 @@
import numpy as np
-from pandas._libs import NaT, iNaT, join as libjoin, lib
+from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib
from pandas._libs.tslibs import timezones
from pandas._typing import Label
from pandas.compat.numpy import function as nv
@@ -41,7 +41,7 @@
from pandas.core.sorting import ensure_key_mapped
from pandas.core.tools.timedeltas import to_timedelta
-from pandas.tseries.frequencies import DateOffset
+from pandas.tseries.offsets import DateOffset, Tick
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
@@ -641,6 +641,7 @@ def intersection(self, other, sort=False):
"""
self._validate_sort_keyword(sort)
self._assert_can_do_setop(other)
+ res_name = get_op_result_name(self, other)
if self.equals(other):
return self._get_reconciled_name_object(other)
@@ -654,12 +655,18 @@ def intersection(self, other, sort=False):
result = Index.intersection(self, other, sort=sort)
if isinstance(result, type(self)):
if result.freq is None:
+ # TODO: no tests rely on this; needed?
result = result._with_freq("infer")
+ assert result.name == res_name
return result
elif not self._can_fast_intersect(other):
result = Index.intersection(self, other, sort=sort)
- result = result._with_freq("infer")
+ assert result.name == res_name
+ # We need to invalidate the freq because Index.intersection
+ # uses _shallow_copy on a view of self._data, which will preserve
+ # self.freq if we're not careful.
+ result = result._with_freq(None)._with_freq("infer")
return result
# to make our life easier, "sort" the two ranges
@@ -674,27 +681,34 @@ def intersection(self, other, sort=False):
start = right[0]
if end < start:
- return type(self)(data=[], dtype=self.dtype, freq=self.freq)
+ return type(self)(data=[], dtype=self.dtype, freq=self.freq, name=res_name)
else:
lslice = slice(*left.slice_locs(start, end))
left_chunk = left._values[lslice]
- return self._shallow_copy(left_chunk)
+ return type(self)._simple_new(left_chunk, name=res_name)
def _can_fast_intersect(self: _T, other: _T) -> bool:
if self.freq is None:
return False
- if other.freq != self.freq:
+ elif other.freq != self.freq:
return False
- if not self.is_monotonic_increasing:
+ elif not self.is_monotonic_increasing:
# Because freq is not None, we must then be monotonic decreasing
return False
- if not self.freq.is_anchored():
- # If freq is not anchored, then despite having matching freqs,
- # we might not "line up"
- return False
+ elif self.freq.is_anchored():
+ # this along with matching freqs ensure that we "line up",
+ # so intersection will preserve freq
+ return True
+
+ elif isinstance(self.freq, Tick):
+ # We "line up" if and only if the difference between two of our points
+ # is a multiple of our freq
+ diff = self[0] - other[0]
+ remainder = diff % self.freq.delta
+ return remainder == Timedelta(0)
return True
@@ -749,6 +763,7 @@ def _fast_union(self, other, sort=None):
right_chunk = right._values[:loc]
dates = concat_compat((left._values, right_chunk))
# With sort being False, we can't infer that result.freq == self.freq
+ # TODO: no tests rely on the _with_freq("infer"); needed?
result = self._shallow_copy(dates)._with_freq("infer")
return result
else:
@@ -781,9 +796,12 @@ def _union(self, other, sort):
if this._can_fast_union(other):
result = this._fast_union(other, sort=sort)
- if result.freq is None:
+ if sort is None:
# In the case where sort is None, _can_fast_union
# implies that result.freq should match self.freq
+ assert result.freq == self.freq, (result.freq, self.freq)
+ elif result.freq is None:
+ # TODO: no tests rely on this; needed?
result = result._with_freq("infer")
return result
else:
diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py
index 0473ecf9de24d..6670b079ddd29 100644
--- a/pandas/tests/indexes/datetimes/test_setops.py
+++ b/pandas/tests/indexes/datetimes/test_setops.py
@@ -222,7 +222,7 @@ def test_intersection(self, tz, sort):
expected3 = date_range("6/1/2000", "6/20/2000", freq="D", name=None)
rng4 = date_range("7/1/2000", "7/31/2000", freq="D", name="idx")
- expected4 = DatetimeIndex([], name="idx")
+ expected4 = DatetimeIndex([], freq="D", name="idx")
for (rng, expected) in [
(rng2, expected2),
@@ -264,7 +264,7 @@ def test_intersection(self, tz, sort):
if sort is None:
expected = expected.sort_values()
tm.assert_index_equal(result, expected)
- assert result.freq is None
+ assert result.freq == expected.freq
# parametrize over both anchored and non-anchored freqs, as they
# have different code paths
diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py
index d7576697435a0..6a2f66cade733 100644
--- a/pandas/tests/indexes/timedeltas/test_setops.py
+++ b/pandas/tests/indexes/timedeltas/test_setops.py
@@ -156,7 +156,7 @@ def test_zero_length_input_index(self, sort):
# if no overlap exists return empty index
(
timedelta_range("1 day", periods=10, freq="h", name="idx")[5:],
- TimedeltaIndex([], name="idx"),
+ TimedeltaIndex([], freq="h", name="idx"),
),
],
)
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index ee87a3f9f5ecd..a1bd6fed32cad 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -128,7 +128,7 @@ def test_partial_setting(self):
df.at[dates[-1] + dates.freq, "A"] = 7
tm.assert_frame_equal(df, expected)
- exp_other = DataFrame({0: 7}, index=[dates[-1] + dates.freq])
+ exp_other = DataFrame({0: 7}, index=dates[-1:] + dates.freq)
expected = pd.concat([df_orig, exp_other], axis=1)
df = df_orig.copy()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Also improve _can_fast_intersect to catch the missing case where we can fast-intersect. Identified that _most_ of the remaining places where we do freq inference are not tested, so may be removeable/deprecateable | https://api.github.com/repos/pandas-dev/pandas/pulls/33904 | 2020-04-30T21:06:56Z | 2020-05-01T20:11:10Z | 2020-05-01T20:11:10Z | 2020-05-01T20:29:54Z |
DEPR: Deprecate try_sort | diff --git a/pandas/core/common.py b/pandas/core/common.py
index 8b152162dc95a..bb911c0617242 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -200,14 +200,6 @@ def count_not_none(*args) -> int:
return sum(x is not None for x in args)
-def try_sort(iterable):
- listed = list(iterable)
- try:
- return sorted(listed)
- except TypeError:
- return listed
-
-
def asarray_tuplesafe(values, dtype=None):
if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")):
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index 0a23d38ace37e..fcce82e7a69db 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -256,8 +256,7 @@ def _sanitize_and_check(indexes):
if list in kinds:
if len(kinds) > 1:
indexes = [
- Index(com.try_sort(x)) if not isinstance(x, Index) else x
- for x in indexes
+ Index(list(x)) if not isinstance(x, Index) else x for x in indexes
]
kinds.remove(list)
else:
| xref #33336
While working on another PR, and @WillAyd brought up `try_sort`, and after a quick look, I don't think `try_sort` is needed in that check method in `indexes/api.py`. (I also dont think it is right to have try_sort there), so deprecate it.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33902 | 2020-04-30T19:45:14Z | 2020-05-05T12:23:18Z | 2020-05-05T12:23:17Z | 2020-05-05T12:23:21Z |
CI: troubleshoot CI | diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 36a581a8ca492..22076eb05db88 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1390,10 +1390,14 @@ def test_constructor_cast_object(self, index):
tm.assert_series_equal(s, exp)
@pytest.mark.parametrize("dtype", [np.datetime64, np.timedelta64])
- def test_constructor_generic_timestamp_no_frequency(self, dtype):
+ def test_constructor_generic_timestamp_no_frequency(self, dtype, request):
# see gh-15524, gh-15987
msg = "dtype has no unit. Please pass in"
+ if np.dtype(dtype).name not in ["timedelta64", "datetime64"]:
+ mark = pytest.mark.xfail(reason="GH#33890 Is assigned ns unit")
+ request.node.add_marker(mark)
+
with pytest.raises(ValueError, match=msg):
Series([], dtype=dtype)
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index 05e708e575a64..bcc0b18134dad 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -382,11 +382,15 @@ def test_astype_categoricaldtype(self):
tm.assert_index_equal(result.cat.categories, Index(["a", "b", "c"]))
@pytest.mark.parametrize("dtype", [np.datetime64, np.timedelta64])
- def test_astype_generic_timestamp_no_frequency(self, dtype):
+ def test_astype_generic_timestamp_no_frequency(self, dtype, request):
# see gh-15524, gh-15987
data = [1]
s = Series(data)
+ if np.dtype(dtype).name not in ["timedelta64", "datetime64"]:
+ mark = pytest.mark.xfail(reason="GH#33890 Is assigned ns unit")
+ request.node.add_marker(mark)
+
msg = (
fr"The '{dtype.__name__}' dtype has no unit\. "
fr"Please pass in '{dtype.__name__}\[ns\]' instead."
| https://api.github.com/repos/pandas-dev/pandas/pulls/33898 | 2020-04-30T17:54:23Z | 2020-05-01T00:20:52Z | 2020-05-01T00:20:52Z | 2021-11-20T23:21:45Z | |
COMPAT: add back block manager constructors to pandas.core.internals API | diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py
index 7f06fb3a7788c..e12e0d7760ea7 100644
--- a/pandas/core/internals/__init__.py
+++ b/pandas/core/internals/__init__.py
@@ -14,7 +14,12 @@
make_block,
)
from pandas.core.internals.concat import concatenate_block_managers
-from pandas.core.internals.managers import BlockManager, SingleBlockManager
+from pandas.core.internals.managers import (
+ BlockManager,
+ SingleBlockManager,
+ create_block_manager_from_arrays,
+ create_block_manager_from_blocks,
+)
__all__ = [
"Block",
@@ -33,4 +38,7 @@
"BlockManager",
"SingleBlockManager",
"concatenate_block_managers",
+ # those two are preserved here for downstream compatibility (GH-33892)
+ "create_block_manager_from_arrays",
+ "create_block_manager_from_blocks",
]
| Those were removed in a for the rest unrelated PR (https://github.com/pandas-dev/pandas/pull/33100, cc @jbrockmendel)
But at least `create_block_manager_from_blocks` is used by dask (in partd: https://github.com/dask/partd/blob/master/partd/pandas.py), so dask's tests are failing with pandas master (cc @TomAugspurger dask isn't testing with pandas master?). But so to be safe just added back both. | https://api.github.com/repos/pandas-dev/pandas/pulls/33892 | 2020-04-30T08:44:04Z | 2020-05-01T06:09:22Z | 2020-05-01T06:09:22Z | 2023-09-30T18:41:14Z |
DOC: Fix Syntax Typo in Indexing | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index fb815b3a975d1..6db757e726792 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -881,7 +881,7 @@ The operators are: ``|`` for ``or``, ``&`` for ``and``, and ``~`` for ``not``.
These **must** be grouped by using parentheses, since by default Python will
evaluate an expression such as ``df['A'] > 2 & df['B'] < 3`` as
``df['A'] > (2 & df['B']) < 3``, while the desired evaluation order is
-``(df['A > 2) & (df['B'] < 3)``.
+``(df['A'] > 2) & (df['B'] < 3)``.
Using a boolean vector to index a Series works exactly as in a NumPy ndarray:
| Please let me know if anything else needs to accompany this change! | https://api.github.com/repos/pandas-dev/pandas/pulls/33887 | 2020-04-30T02:08:42Z | 2020-04-30T07:02:59Z | 2020-04-30T07:02:59Z | 2020-04-30T07:02:59Z |
CLN: address TODOs | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 14efab735fa7d..e3b1e1ec8cb6a 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -589,7 +589,7 @@ def array_equivalent_object(left: object[:], right: object[:]) -> bool:
except TypeError as err:
# Avoid raising TypeError on tzawareness mismatch
# TODO: This try/except can be removed if/when Timestamp
- # comparisons are change dto match datetime, see GH#28507
+ # comparisons are changed to match datetime, see GH#28507
if "tz-naive and tz-aware" in str(err):
return False
raise
@@ -2346,8 +2346,6 @@ def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=Tr
if cnp.PyArray_IsZeroDim(val):
# unbox 0-dim arrays, GH#690
- # TODO: is there a faster way to unbox?
- # item_from_zerodim?
val = val.item()
result[i] = val
@@ -2388,8 +2386,6 @@ def map_infer(ndarray arr, object f, bint convert=True):
if cnp.PyArray_IsZeroDim(val):
# unbox 0-dim arrays, GH#690
- # TODO: is there a faster way to unbox?
- # item_from_zerodim?
val = val.item()
result[i] = val
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index c5092c8630f06..7fc22ebf11987 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -1516,10 +1516,6 @@ class Timedelta(_Timedelta):
def __rmod__(self, other):
# Naive implementation, room for optimization
- if hasattr(other, 'dtype') and other.dtype.kind == 'i':
- # TODO: Remove this check with backwards-compat shim
- # for integer / Timedelta is removed.
- raise TypeError(f'Invalid dtype {other.dtype} for __mod__')
return self.__rdivmod__(other)[1]
def __divmod__(self, other):
@@ -1529,10 +1525,6 @@ class Timedelta(_Timedelta):
def __rdivmod__(self, other):
# Naive implementation, room for optimization
- if hasattr(other, 'dtype') and other.dtype.kind == 'i':
- # TODO: Remove this check with backwards-compat shim
- # for integer / Timedelta is removed.
- raise TypeError(f'Invalid dtype {other.dtype} for __mod__')
div = other // self
return div, other - div * self
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 8b6ed002b3f47..27f4185d11259 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1522,13 +1522,9 @@ def __rsub__(self, other):
# TODO: Can we simplify/generalize these cases at all?
raise TypeError(f"cannot subtract {type(self).__name__} from {other.dtype}")
elif is_timedelta64_dtype(self.dtype):
- if lib.is_integer(other) or is_integer_dtype(other):
- # need to subtract before negating, since that flips freq
- # -self flips self.freq, messing up results
- return -(self - other)
-
return (-self) + other
+ # We get here with e.g. datetime objects
return -(self - other)
def __iadd__(self, other):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f8cb99e2b2e75..f86ae77323bb7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8989,7 +8989,6 @@ def _AXIS_NAMES(self) -> Dict[int, str]:
def _from_nested_dict(data):
- # TODO: this should be seriously cythonized
new_data = collections.defaultdict(dict)
for index, s in data.items():
for col, v in s.items():
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 4254fafa8bb3a..0f4eca260f3cf 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -151,7 +151,6 @@ def index_arithmetic_method(self, other):
return Index(result)
name = f"__{op.__name__}__"
- # TODO: docstring?
return set_function_name(index_arithmetic_method, name, cls)
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 135361c8c0962..54892d5656990 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -668,10 +668,14 @@ def intersection(self, other, sort=False):
if self.equals(other):
return self._get_reconciled_name_object(other)
- if not is_dtype_equal(self.dtype, other.dtype):
- # TODO: fastpath for if we have a different PeriodDtype
- this = self.astype("O")
- other = other.astype("O")
+ elif is_object_dtype(other.dtype):
+ return self.astype("O").intersection(other, sort=sort)
+
+ elif not is_dtype_equal(self.dtype, other.dtype):
+ # We can infer that the intersection is empty.
+ # assert_can_do_setop ensures that this is not just a mismatched freq
+ this = self[:0].astype("O")
+ other = other[:0].astype("O")
return this.intersection(other, sort=sort)
return self._setop(other, sort, opname="intersection")
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index e9bbd915df768..0913c47020820 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -1,4 +1,3 @@
-# TODO: Needs a better name; too many modules are already called "concat"
from collections import defaultdict
import copy
from typing import List
diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py
index 6ebcaf6b72c45..bd8c3be271505 100644
--- a/pandas/io/sas/sasreader.py
+++ b/pandas/io/sas/sasreader.py
@@ -7,7 +7,7 @@
from pandas.io.common import stringify_path
-# TODO: replace with Protocol in Python 3.8
+# TODO(PY38): replace with Protocol in Python 3.8
class ReaderBase(metaclass=ABCMeta):
"""
Protocol for XportReader and SAS7BDATReader classes.
| - [ ] 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/33886 | 2020-04-30T01:54:40Z | 2020-05-01T19:35:44Z | 2020-05-01T19:35:44Z | 2020-05-01T20:17:09Z |
BUG: recognize M8[ns, tzstr] | diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 8fe2b3c60d6d0..be43e3a6c856b 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -798,6 +798,8 @@ def __hash__(self) -> int:
def __eq__(self, other: Any) -> bool:
if isinstance(other, str):
+ if other.startswith("M8["):
+ other = "datetime64[" + other[3:]
return other == self.name
return (
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index b9c8f3a8dd494..1708139a397ab 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -75,6 +75,10 @@ def test_numpy_string_dtype(self):
"datetime64[ns, US/Eastern]",
"datetime64[ns, Asia/Tokyo]",
"datetime64[ns, UTC]",
+ # GH#33885 check that the M8 alias is understood
+ "M8[ns, US/Eastern]",
+ "M8[ns, Asia/Tokyo]",
+ "M8[ns, UTC]",
],
)
def test_datetimetz_dtype(self, dtype):
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 519f2f3eead1c..b55ff92e3f6a4 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -278,12 +278,14 @@ def test_is_dtype(self, dtype):
assert not DatetimeTZDtype.is_dtype(None)
assert DatetimeTZDtype.is_dtype(dtype)
assert DatetimeTZDtype.is_dtype("datetime64[ns, US/Eastern]")
+ assert DatetimeTZDtype.is_dtype("M8[ns, US/Eastern]")
assert not DatetimeTZDtype.is_dtype("foo")
assert DatetimeTZDtype.is_dtype(DatetimeTZDtype("ns", "US/Pacific"))
assert not DatetimeTZDtype.is_dtype(np.float64)
def test_equality(self, dtype):
assert is_dtype_equal(dtype, "datetime64[ns, US/Eastern]")
+ assert is_dtype_equal(dtype, "M8[ns, US/Eastern]")
assert is_dtype_equal(dtype, DatetimeTZDtype("ns", "US/Eastern"))
assert not is_dtype_equal(dtype, "foo")
assert not is_dtype_equal(dtype, DatetimeTZDtype("ns", "CET"))
@@ -294,6 +296,8 @@ def test_equality(self, dtype):
# numpy compat
assert is_dtype_equal(np.dtype("M8[ns]"), "datetime64[ns]")
+ assert dtype == "M8[ns, US/Eastern]"
+
def test_basic(self, dtype):
assert is_datetime64tz_dtype(dtype)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
ATM `dtype == "M8[ns, UTC]"` fails while `dtype == "datetime64[ns, UTC]"` succeeds | https://api.github.com/repos/pandas-dev/pandas/pulls/33885 | 2020-04-30T01:42:14Z | 2020-05-09T19:27:41Z | 2020-05-09T19:27:41Z | 2020-05-09T21:38:34Z |
BUG: Preserve Series/DataFrame subclasses through groupby operations | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 40adeb28d47b6..7b046cb3a515b 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -703,6 +703,7 @@ Groupby/resample/rolling
- 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`)
+- Bug in :meth:`GroupBy.agg`, :meth:`GroupBy.transform`, and :meth:`GroupBy.resample` where subclasses are not preserved (:issue:`28330`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f8cb99e2b2e75..8d94d61a10739 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8524,7 +8524,7 @@ def idxmin(self, axis=0, skipna=True) -> Series:
indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna)
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
- return Series(result, index=self._get_agg_axis(axis))
+ return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def idxmax(self, axis=0, skipna=True) -> Series:
"""
@@ -8591,7 +8591,7 @@ def idxmax(self, axis=0, skipna=True) -> Series:
indices = nanops.nanargmax(self.values, axis=axis, skipna=skipna)
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
- return Series(result, index=self._get_agg_axis(axis))
+ return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def _get_agg_axis(self, axis_num: int) -> Index:
"""
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index b35798079ba7f..04a3524fed480 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -330,7 +330,7 @@ def _aggregate_multiple_funcs(self, arg):
# let higher level handle
return results
- return DataFrame(results, columns=columns)
+ return self.obj._constructor_expanddim(results, columns=columns)
def _wrap_series_output(
self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]], index: Index,
@@ -359,10 +359,12 @@ def _wrap_series_output(
result: Union[Series, DataFrame]
if len(output) > 1:
- result = DataFrame(indexed_output, index=index)
+ result = self.obj._constructor_expanddim(indexed_output, index=index)
result.columns = columns
else:
- result = Series(indexed_output[0], index=index, name=columns[0])
+ result = self.obj._constructor(
+ indexed_output[0], index=index, name=columns[0]
+ )
return result
@@ -421,7 +423,9 @@ def _wrap_transformed_output(
def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if len(keys) == 0:
# GH #6265
- return Series([], name=self._selection_name, index=keys, dtype=np.float64)
+ return self.obj._constructor(
+ [], name=self._selection_name, index=keys, dtype=np.float64
+ )
def _get_index() -> Index:
if self.grouper.nkeys > 1:
@@ -433,7 +437,9 @@ def _get_index() -> Index:
if isinstance(values[0], dict):
# GH #823 #24880
index = _get_index()
- result = self._reindex_output(DataFrame(values, index=index))
+ result = self._reindex_output(
+ self.obj._constructor_expanddim(values, index=index)
+ )
# if self.observed is False,
# keep all-NaN rows created while re-indexing
result = result.stack(dropna=self.observed)
@@ -447,7 +453,9 @@ def _get_index() -> Index:
return self._concat_objects(keys, values, not_indexed_same=not_indexed_same)
else:
# GH #6265 #24880
- result = Series(data=values, index=_get_index(), name=self._selection_name)
+ result = self.obj._constructor(
+ data=values, index=_get_index(), name=self._selection_name
+ )
return self._reindex_output(result)
def _aggregate_named(self, func, *args, **kwargs):
@@ -527,7 +535,7 @@ def _transform_general(
result = concat(results).sort_index()
else:
- result = Series(dtype=np.float64)
+ result = self.obj._constructor(dtype=np.float64)
# we will only try to coerce the result type if
# we have a numeric dtype, as these are *always* user-defined funcs
@@ -550,7 +558,7 @@ def _transform_fast(self, result, func_nm: str) -> Series:
out = algorithms.take_1d(result._values, ids)
if cast:
out = maybe_cast_result(out, self.obj, how=func_nm)
- return Series(out, index=self.obj.index, name=self.obj.name)
+ return self.obj._constructor(out, index=self.obj.index, name=self.obj.name)
def filter(self, func, dropna=True, *args, **kwargs):
"""
@@ -651,7 +659,7 @@ def nunique(self, dropna: bool = True) -> Series:
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
- result = Series(res, index=ri, name=self._selection_name)
+ result = self.obj._constructor(res, index=ri, name=self._selection_name)
return self._reindex_output(result, fill_value=0)
@doc(Series.describe)
@@ -753,7 +761,7 @@ def value_counts(
if is_integer_dtype(out):
out = ensure_int64(out)
- return Series(out, index=mi, name=self._selection_name)
+ return self.obj._constructor(out, index=mi, name=self._selection_name)
# for compat. with libgroupby.value_counts need to ensure every
# bin is present at every index level, null filled with zeros
@@ -785,7 +793,7 @@ def build_codes(lev_codes: np.ndarray) -> np.ndarray:
if is_integer_dtype(out):
out = ensure_int64(out)
- return Series(out, index=mi, name=self._selection_name)
+ return self.obj._constructor(out, index=mi, name=self._selection_name)
def count(self) -> Series:
"""
@@ -804,7 +812,7 @@ def count(self) -> Series:
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
- result = Series(
+ result = self.obj._constructor(
out,
index=self.grouper.result_index,
name=self._selection_name,
@@ -1202,11 +1210,11 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame:
if cannot_agg:
result_columns = result_columns.drop(cannot_agg)
- return DataFrame(result, columns=result_columns)
+ return self.obj._constructor(result, columns=result_columns)
def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if len(keys) == 0:
- return DataFrame(index=keys)
+ return self.obj._constructor(index=keys)
key_names = self.grouper.names
@@ -1216,7 +1224,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if first_not_none is None:
# GH9684. If all values are None, then this will throw an error.
# We'd prefer it return an empty dataframe.
- return DataFrame()
+ return self.obj._constructor()
elif isinstance(first_not_none, DataFrame):
return self._concat_objects(keys, values, not_indexed_same=not_indexed_same)
elif self.grouper.groupings is not None:
@@ -1247,13 +1255,13 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# make Nones an empty object
if first_not_none is None:
- return DataFrame()
+ return self.obj._constructor()
elif isinstance(first_not_none, NDFrame):
# this is to silence a DeprecationWarning
# TODO: Remove when default dtype of empty Series is object
kwargs = first_not_none._construct_axes_dict()
- if first_not_none._constructor is Series:
+ if isinstance(first_not_none, Series):
backup = create_series_with_explicit_dtype(
**kwargs, dtype_if_empty=object
)
@@ -1320,7 +1328,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
or isinstance(key_index, MultiIndex)
):
stacked_values = np.vstack([np.asarray(v) for v in values])
- result = DataFrame(
+ result = self.obj._constructor(
stacked_values, index=key_index, columns=index
)
else:
@@ -1337,7 +1345,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
result.columns = index
elif isinstance(v, ABCSeries):
stacked_values = np.vstack([np.asarray(v) for v in values])
- result = DataFrame(
+ result = self.obj._constructor(
stacked_values.T, index=v.index, columns=key_index
)
else:
@@ -1345,7 +1353,9 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# fall through to the outer else clause
# TODO: sure this is right? we used to do this
# after raising AttributeError above
- return Series(values, index=key_index, name=self._selection_name)
+ return self.obj._constructor_sliced(
+ values, index=key_index, name=self._selection_name
+ )
# if we have date/time like in the original, then coerce dates
# as we are stacking can easily have object dtypes here
@@ -1362,7 +1372,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# self._selection_name not passed through to Series as the
# result should not take the name of original selection
# of columns
- return Series(values, index=key_index)
+ return self.obj._constructor_sliced(values, index=key_index)
else:
# Handle cases like BinGrouper
@@ -1396,7 +1406,9 @@ def _transform_general(
if cache_key not in NUMBA_FUNC_CACHE:
NUMBA_FUNC_CACHE[cache_key] = numba_func
# Return the result as a DataFrame for concatenation later
- res = DataFrame(res, index=group.index, columns=group.columns)
+ res = self.obj._constructor(
+ res, index=group.index, columns=group.columns
+ )
else:
# Try slow path and fast path.
try:
@@ -1419,7 +1431,7 @@ def _transform_general(
r.columns = group.columns
r.index = group.index
else:
- r = DataFrame(
+ r = self.obj._constructor(
np.concatenate([res.values] * len(group.index)).reshape(
group.shape
),
@@ -1495,7 +1507,9 @@ def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame:
res = maybe_cast_result(res, obj.iloc[:, i], how=func_nm)
output.append(res)
- return DataFrame._from_arrays(output, columns=result.columns, index=obj.index)
+ return self.obj._constructor._from_arrays(
+ output, columns=result.columns, index=obj.index
+ )
def _define_paths(self, func, *args, **kwargs):
if isinstance(func, str):
@@ -1557,7 +1571,7 @@ def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame:
if len(output) < len(obj.columns):
columns = columns.take(inds)
- return DataFrame(output, index=obj.index, columns=columns)
+ return self.obj._constructor(output, index=obj.index, columns=columns)
def filter(self, func, dropna=True, *args, **kwargs):
"""
@@ -1672,9 +1686,11 @@ def _wrap_frame_output(self, result, obj) -> DataFrame:
result_index = self.grouper.levels[0]
if self.axis == 0:
- return DataFrame(result, index=obj.columns, columns=result_index).T
+ return self.obj._constructor(
+ result, index=obj.columns, columns=result_index
+ ).T
else:
- return DataFrame(result, index=obj.index, columns=result_index)
+ return self.obj._constructor(result, index=obj.index, columns=result_index)
def _get_data_to_aggregate(self) -> BlockManager:
obj = self._obj_with_exclusions
@@ -1718,7 +1734,7 @@ def _wrap_aggregated_output(
indexed_output = {key.position: val for key, val in output.items()}
columns = Index(key.label for key in output)
- result = DataFrame(indexed_output)
+ result = self.obj._constructor(indexed_output)
result.columns = columns
if not self.as_index:
@@ -1751,7 +1767,7 @@ def _wrap_transformed_output(
indexed_output = {key.position: val for key, val in output.items()}
columns = Index(key.label for key in output)
- result = DataFrame(indexed_output)
+ result = self.obj._constructor(indexed_output)
result.columns = columns
result.index = self.obj.index
@@ -1761,14 +1777,14 @@ def _wrap_agged_blocks(self, blocks: "Sequence[Block]", items: Index) -> DataFra
if not self.as_index:
index = np.arange(blocks[0].values.shape[-1])
mgr = BlockManager(blocks, axes=[items, index])
- result = DataFrame(mgr)
+ result = self.obj._constructor(mgr)
self._insert_inaxis_grouper_inplace(result)
result = result._consolidate()
else:
index = self.grouper.result_index
mgr = BlockManager(blocks, axes=[items, index])
- result = DataFrame(mgr)
+ result = self.obj._constructor(mgr)
if self.axis == 1:
result = result.T
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 81c3fd7ad9e89..08d18397d7225 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1182,6 +1182,14 @@ class GroupBy(_GroupBy[FrameOrSeries]):
more
"""
+ @property
+ def _obj_1d_constructor(self) -> Type["Series"]:
+ # GH28330 preserve subclassed Series/DataFrames
+ if isinstance(self.obj, DataFrame):
+ return self.obj._constructor_sliced
+ assert isinstance(self.obj, Series)
+ return self.obj._constructor
+
def _bool_agg(self, val_test, skipna):
"""
Shared func to call any / all Cython GroupBy implementations.
@@ -1420,8 +1428,11 @@ def size(self):
"""
result = self.grouper.size()
- if isinstance(self.obj, Series):
- result.name = self.obj.name
+ # GH28330 preserve subclassed Series/DataFrames through calls
+ if issubclass(self.obj._constructor, Series):
+ result = self._obj_1d_constructor(result, name=self.obj.name)
+ else:
+ result = self._obj_1d_constructor(result)
return self._reindex_output(result, fill_value=0)
@classmethod
@@ -2116,7 +2127,7 @@ def ngroup(self, ascending: bool = True):
"""
with _group_selection_context(self):
index = self._selected_obj.index
- result = Series(self.grouper.group_info[0], index)
+ result = self._obj_1d_constructor(self.grouper.group_info[0], index)
if not ascending:
result = self.ngroups - 1 - result
return result
@@ -2178,7 +2189,7 @@ def cumcount(self, ascending: bool = True):
with _group_selection_context(self):
index = self._selected_obj.index
cumcounts = self._cumcount_array(ascending=ascending)
- return Series(cumcounts, index)
+ return self._obj_1d_constructor(cumcounts, index)
@Substitution(name="groupby")
@Appender(_common_see_also)
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 2f66cbf44788d..28dfaea8ed425 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -469,7 +469,9 @@ def get_result(self):
# combine as columns in a frame
else:
data = dict(zip(range(len(self.objs)), self.objs))
- cons = DataFrame
+
+ # GH28330 Preserves subclassed objects through concat
+ cons = self.objs[0]._constructor_expanddim
index, columns = self.new_axes
df = cons(data, index=index)
diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py
index 16bf651829a04..f4f7cc5c1a7d6 100644
--- a/pandas/tests/frame/test_subclass.py
+++ b/pandas/tests/frame/test_subclass.py
@@ -573,3 +573,17 @@ def test_subclassed_boolean_reductions(self, all_boolean_reductions):
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
result = getattr(df, all_boolean_reductions)()
assert isinstance(result, tm.SubclassedSeries)
+
+ def test_idxmin_preserves_subclass(self):
+ # GH 28330
+
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.idxmin()
+ assert isinstance(result, tm.SubclassedSeries)
+
+ def test_idxmax_preserves_subclass(self):
+ # GH 28330
+
+ df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
+ result = df.idxmax()
+ assert isinstance(result, tm.SubclassedSeries)
diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py
new file mode 100644
index 0000000000000..6adae19005c3a
--- /dev/null
+++ b/pandas/tests/groupby/test_groupby_subclass.py
@@ -0,0 +1,77 @@
+from datetime import datetime
+
+import numpy as np
+import pytest
+
+from pandas import DataFrame, Series
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ tm.SubclassedDataFrame({"A": np.arange(0, 10)}),
+ tm.SubclassedSeries(np.arange(0, 10), name="A"),
+ ],
+)
+def test_groupby_preserves_subclass(obj, groupby_func):
+ # GH28330 -- preserve subclass through groupby operations
+
+ if isinstance(obj, Series) and groupby_func in {"corrwith"}:
+ pytest.skip("Not applicable")
+
+ grouped = obj.groupby(np.arange(0, 10))
+
+ # Groups should preserve subclass type
+ assert isinstance(grouped.get_group(0), type(obj))
+
+ args = []
+ if groupby_func in {"fillna", "nth"}:
+ args.append(0)
+ elif groupby_func == "corrwith":
+ args.append(obj)
+ elif groupby_func == "tshift":
+ args.extend([0, 0])
+
+ result1 = getattr(grouped, groupby_func)(*args)
+ result2 = grouped.agg(groupby_func, *args)
+
+ # Reduction or transformation kernels should preserve type
+ slices = {"ngroup", "cumcount", "size"}
+ if isinstance(obj, DataFrame) and groupby_func in slices:
+ assert isinstance(result1, obj._constructor_sliced)
+ else:
+ assert isinstance(result1, type(obj))
+
+ # Confirm .agg() groupby operations return same results
+ if isinstance(result1, DataFrame):
+ tm.assert_frame_equal(result1, result2)
+ else:
+ tm.assert_series_equal(result1, result2)
+
+
+@pytest.mark.parametrize(
+ "obj", [DataFrame, tm.SubclassedDataFrame],
+)
+def test_groupby_resample_preserves_subclass(obj):
+ # GH28330 -- preserve subclass through groupby.resample()
+
+ df = obj(
+ {
+ "Buyer": "Carl Carl Carl Carl Joe Carl".split(),
+ "Quantity": [18, 3, 5, 1, 9, 3],
+ "Date": [
+ datetime(2013, 9, 1, 13, 0),
+ datetime(2013, 9, 1, 13, 5),
+ datetime(2013, 10, 1, 20, 0),
+ datetime(2013, 10, 3, 10, 0),
+ datetime(2013, 12, 2, 12, 0),
+ datetime(2013, 9, 2, 14, 0),
+ ],
+ }
+ )
+ df = df.set_index("Date")
+
+ # Confirm groupby.resample() preserves dataframe type
+ result = df.groupby("Buyer").resample("5D").sum()
+ assert isinstance(result, obj)
diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index 6625ab86cfed4..b7fd12326bcfe 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -2817,3 +2817,17 @@ def test_duplicate_keys(keys):
)
expected = DataFrame(expected_values, columns=expected_columns)
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "obj",
+ [
+ tm.SubclassedDataFrame({"A": np.arange(0, 10)}),
+ tm.SubclassedSeries(np.arange(0, 10), name="A"),
+ ],
+)
+def test_concat_preserves_subclass(obj):
+ # GH28330 -- preserve subclass
+
+ result = concat([obj, obj])
+ assert isinstance(result, type(obj))
| This pull request fixes a bug that caused subclassed Series/DataFrames to revert to `pd.Series` and `pd.DataFrame` after `groupby()` operations. This is a follow-up on a previously abandoned pull request (#28573)
- [x] closes #28330
- [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/33884 | 2020-04-30T00:30:36Z | 2020-05-13T14:52:10Z | 2020-05-13T14:52:10Z | 2020-05-13T20:28:12Z |
BUG: TimedeltaArray+Period, PeriodArray-TimedeltaArray | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index e56014ed866ca..ff077f1de3056 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -640,6 +640,7 @@ Datetimelike
- :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`
- Bug in :meth:`DatetimeIndex.intersection` and :meth:`TimedeltaIndex.intersection` with results not having the correct ``name`` attribute (:issue:`33904`)
- Bug in :meth:`DatetimeArray.__setitem__`, :meth:`TimedeltaArray.__setitem__`, :meth:`PeriodArray.__setitem__` incorrectly allowing values with ``int64`` dtype to be silently cast (:issue:`33717`)
+- Bug in subtracting :class:`TimedeltaIndex` from :class:`Period` incorrectly raising ``TypeError`` in some cases where it should succeed and ``IncompatibleFrequency`` in some cases where it should raise ``TypeError`` (:issue:`33883`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 357ef5f5e42ab..c3203da322851 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1187,6 +1187,10 @@ def _sub_period(self, other):
# Overridden by PeriodArray
raise TypeError(f"cannot subtract Period from a {type(self).__name__}")
+ def _add_period(self, other: Period):
+ # Overriden by TimedeltaArray
+ raise TypeError(f"cannot add Period to a {type(self).__name__}")
+
def _add_offset(self, offset):
raise AbstractMethodError(self)
@@ -1391,6 +1395,8 @@ def __add__(self, other):
result = self._add_offset(other)
elif isinstance(other, (datetime, np.datetime64)):
result = self._add_datetimelike_scalar(other)
+ elif isinstance(other, Period) and is_timedelta64_dtype(self.dtype):
+ result = self._add_period(other)
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 8be714820d18b..713e7ca7712d2 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -32,7 +32,12 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import PeriodDtype
-from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndexClass,
+ ABCPeriodIndex,
+ ABCSeries,
+ ABCTimedeltaArray,
+)
from pandas.core.dtypes.missing import isna, notna
import pandas.core.algorithms as algos
@@ -676,7 +681,9 @@ def _add_timedelta_arraylike(self, other):
"""
if not isinstance(self.freq, Tick):
# We cannot add timedelta-like to non-tick PeriodArray
- raise raise_on_incompatible(self, other)
+ raise TypeError(
+ f"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}"
+ )
if not np.all(isna(other)):
delta = self._check_timedeltalike_freq_compat(other)
@@ -753,7 +760,7 @@ def raise_on_incompatible(left, right):
Exception to be raised by the caller.
"""
# GH#24283 error message format depends on whether right is scalar
- if isinstance(right, np.ndarray) or right is None:
+ if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None:
other_freq = None
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
other_freq = right.freqstr
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 164d45334033e..4b84b3ea8b46a 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -4,7 +4,7 @@
import numpy as np
from pandas._libs import lib, tslibs
-from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT
+from pandas._libs.tslibs import NaT, Period, Timedelta, Timestamp, iNaT
from pandas._libs.tslibs.fields import get_timedelta_field
from pandas._libs.tslibs.timedeltas import (
array_to_timedelta64,
@@ -404,6 +404,17 @@ def _add_offset(self, other):
f"cannot add the type {type(other).__name__} to a {type(self).__name__}"
)
+ def _add_period(self, other: Period):
+ """
+ Add a Period object.
+ """
+ # We will wrap in a PeriodArray and defer to the reversed operation
+ from .period import PeriodArray
+
+ i8vals = np.broadcast_to(other.ordinal, self.shape)
+ oth = PeriodArray(i8vals, freq=other.freq)
+ return oth + self
+
def _add_datetime_arraylike(self, other):
"""
Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 3b3f5cb90bb31..9fc6568a019b6 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -10,7 +10,7 @@
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import Period, PeriodIndex, Series, period_range
+from pandas import Period, PeriodIndex, Series, TimedeltaIndex, Timestamp, period_range
import pandas._testing as tm
from pandas.core import ops
from pandas.core.arrays import TimedeltaArray
@@ -730,13 +730,13 @@ def test_pi_add_sub_td64_array_non_tick_raises(self):
tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
tdarr = tdi.values
- msg = r"Input has different freq=None from PeriodArray\(freq=Q-DEC\)"
- with pytest.raises(IncompatibleFrequency, match=msg):
+ msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]"
+ with pytest.raises(TypeError, match=msg):
rng + tdarr
- with pytest.raises(IncompatibleFrequency, match=msg):
+ with pytest.raises(TypeError, match=msg):
tdarr + rng
- with pytest.raises(IncompatibleFrequency, match=msg):
+ with pytest.raises(TypeError, match=msg):
rng - tdarr
msg = r"cannot subtract PeriodArray from timedelta64\[ns\]"
with pytest.raises(TypeError, match=msg):
@@ -773,6 +773,48 @@ def test_pi_add_sub_td64_array_tick(self):
with pytest.raises(TypeError, match=msg):
tdi - rng
+ @pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "H"])
+ @pytest.mark.parametrize("tdi_freq", [None, "H"])
+ def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq):
+ box = box_with_array
+ xbox = box if box is not tm.to_array else pd.Index
+
+ tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
+ dti = Timestamp("2018-03-07 17:16:40") + tdi
+ pi = dti.to_period(pi_freq)
+
+ # TODO: parametrize over box for pi?
+ td64obj = tm.box_expected(tdi, box)
+
+ if pi_freq == "H":
+ result = pi - td64obj
+ expected = (pi.to_timestamp("S") - tdi).to_period(pi_freq)
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+ # Subtract from scalar
+ result = pi[0] - td64obj
+ expected = (pi[0].to_timestamp("S") - tdi).to_period(pi_freq)
+ expected = tm.box_expected(expected, box)
+ tm.assert_equal(result, expected)
+
+ elif pi_freq == "D":
+ # Tick, but non-compatible
+ msg = "Input has different freq=None from PeriodArray"
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ pi - td64obj
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ pi[0] - td64obj
+
+ else:
+ # With non-Tick freq, we could not add timedelta64 array regardless
+ # of what its resolution is
+ msg = "Cannot add or subtract timedelta64"
+ with pytest.raises(TypeError, match=msg):
+ pi - td64obj
+ with pytest.raises(TypeError, match=msg):
+ pi[0] - td64obj
+
# -----------------------------------------------------------------
# operations with array/Index of DateOffset objects
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index d540ff923c929..180364420b021 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1081,16 +1081,9 @@ def test_td64arr_sub_periodlike(self, box_with_array, tdi_freq, pi_freq):
with pytest.raises(TypeError, match=msg):
tdi - pi
- # FIXME: don't leave commented-out
- # FIXME: this raises with period scalar but not with PeriodIndex?
- # with pytest.raises(TypeError):
- # pi - tdi
-
# GH#13078 subtraction of Period scalar not supported
with pytest.raises(TypeError, match=msg):
tdi - pi[0]
- with pytest.raises(TypeError, match=msg):
- pi[0] - tdi
@pytest.mark.parametrize(
"other",
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
motivated by the FIXME comment in test_timedelta64.py | https://api.github.com/repos/pandas-dev/pandas/pulls/33883 | 2020-04-29T23:38:45Z | 2020-05-13T15:52:37Z | 2020-05-13T15:52:37Z | 2020-05-13T15:59:33Z |
TST: stricter xfails, catch/suppress warnings | diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index c20a9567e9ff8..8b9e5cd371a90 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -231,22 +231,6 @@ def box(request):
return request.param
-@pytest.fixture(
- params=[
- pd.Index,
- pd.Series,
- pytest.param(pd.DataFrame, marks=pytest.mark.xfail),
- tm.to_array,
- ],
- ids=id_func,
-)
-def box_df_fail(request):
- """
- Fixture equivalent to `box` fixture but xfailing the DataFrame case.
- """
- return request.param
-
-
@pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func)
def box_with_array(request):
"""
diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py
index d7c312b2fda1b..66526204a6208 100644
--- a/pandas/tests/arithmetic/test_interval.py
+++ b/pandas/tests/arithmetic/test_interval.py
@@ -126,12 +126,15 @@ def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
expected = self.elementwise_comparison(op, array, other)
tm.assert_numpy_array_equal(result, expected)
- def test_compare_scalar_na(self, op, array, nulls_fixture):
+ def test_compare_scalar_na(self, op, array, nulls_fixture, request):
result = op(array, nulls_fixture)
expected = self.elementwise_comparison(op, array, nulls_fixture)
- if nulls_fixture is pd.NA and array.dtype != pd.IntervalDtype("int"):
- pytest.xfail("broken for non-integer IntervalArray; see GH 31882")
+ if nulls_fixture is pd.NA and array.dtype != pd.IntervalDtype("int64"):
+ mark = pytest.mark.xfail(
+ reason="broken for non-integer IntervalArray; see GH 31882"
+ )
+ request.node.add_marker(mark)
tm.assert_numpy_array_equal(result, expected)
@@ -207,13 +210,15 @@ def test_compare_list_like_object(self, op, array, other):
expected = self.elementwise_comparison(op, array, other)
tm.assert_numpy_array_equal(result, expected)
- def test_compare_list_like_nan(self, op, array, nulls_fixture):
+ def test_compare_list_like_nan(self, op, array, nulls_fixture, request):
other = [nulls_fixture] * 4
result = op(array, other)
expected = self.elementwise_comparison(op, array, other)
- if nulls_fixture is pd.NA:
- pytest.xfail("broken for non-integer IntervalArray; see GH 31882")
+ if nulls_fixture is pd.NA and array.dtype.subtype != "i8":
+ reason = "broken for non-integer IntervalArray; see GH 31882"
+ mark = pytest.mark.xfail(reason=reason)
+ request.node.add_marker(mark)
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py
index 87df5959e6221..9248c185bccd7 100644
--- a/pandas/tests/indexes/test_index_new.py
+++ b/pandas/tests/indexes/test_index_new.py
@@ -83,7 +83,7 @@ def test_constructor_infer_periodindex(self):
],
)
def test_constructor_infer_nat_dt_like(
- self, pos, klass, dtype, ctor, nulls_fixture
+ self, pos, klass, dtype, ctor, nulls_fixture, request
):
expected = klass([NaT, NaT])
assert expected.dtype == dtype
@@ -92,7 +92,8 @@ def test_constructor_infer_nat_dt_like(
if nulls_fixture is NA:
expected = Index([NA, NaT])
- pytest.xfail("Broken with np.NaT ctor; see GH 31884")
+ mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884")
+ request.node.add_marker(mark)
result = Index(data)
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index 84bc29ebc65e0..b27b028694d20 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -235,6 +235,11 @@ def test_read_expands_user_home_dir(
),
],
)
+ @pytest.mark.filterwarnings(
+ "ignore:This method will be removed in future versions. "
+ r"Use 'tree.iter\(\)' or 'list\(tree.iter\(\)\)' instead."
+ ":PendingDeprecationWarning"
+ )
def test_read_fspath_all(self, reader, module, path, datapath):
pytest.importorskip(module)
path = datapath(*path)
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index b85a2affc4e4b..7dcb692e29337 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -1456,7 +1456,9 @@ def test_add_matplotlib_datetime64(self):
# ax.xaxis.converter with a DatetimeConverter
s = Series(np.random.randn(10), index=date_range("1970-01-02", periods=10))
ax = s.plot()
- ax.plot(s.index, s.values, color="g")
+ with tm.assert_produces_warning(DeprecationWarning):
+ # multi-dimensional indexing
+ ax.plot(s.index, s.values, color="g")
l1, l2 = ax.lines
tm.assert_numpy_array_equal(l1.get_xydata(), l2.get_xydata())
| Remove box_df_fail which is no longer used | https://api.github.com/repos/pandas-dev/pandas/pulls/33882 | 2020-04-29T23:18:14Z | 2020-05-02T15:35:45Z | 2020-05-02T15:35:45Z | 2020-05-02T16:34:09Z |
CLN: address FIXME comments | diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py
index 8260684c02ea6..11c59a0903440 100644
--- a/pandas/plotting/_matplotlib/converter.py
+++ b/pandas/plotting/_matplotlib/converter.py
@@ -387,23 +387,6 @@ def __call__(self):
return []
# We need to cap at the endpoints of valid datetime
-
- # FIXME: dont leave commented-out
- # TODO(wesm) unused?
- # if dmin > dmax:
- # dmax, dmin = dmin, dmax
- # delta = relativedelta(dmax, dmin)
- # try:
- # start = dmin - delta
- # except ValueError:
- # start = _from_ordinal(1.0)
-
- # try:
- # stop = dmax + delta
- # except ValueError:
- # # The magic number!
- # stop = _from_ordinal(3652059.9999999)
-
nmax, nmin = dates.date2num((dmax, dmin))
num = (nmax - nmin) * 86400 * 1000
@@ -449,27 +432,7 @@ def autoscale(self):
"""
Set the view limits to include the data range.
"""
- dmin, dmax = self.datalim_to_dt()
- if dmin > dmax:
- dmax, dmin = dmin, dmax
-
# We need to cap at the endpoints of valid datetime
-
- # FIXME: dont leave commented-out
- # TODO(wesm): unused?
-
- # delta = relativedelta(dmax, dmin)
- # try:
- # start = dmin - delta
- # except ValueError:
- # start = _from_ordinal(1.0)
-
- # try:
- # stop = dmax + delta
- # except ValueError:
- # # The magic number!
- # stop = _from_ordinal(3652059.9999999)
-
dmin, dmax = self.datalim_to_dt()
vmin = dates.date2num(dmin)
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index 0b8b334e53d68..50b72698629bb 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -356,7 +356,5 @@ class TestUnaryOps(base.BaseUnaryOpsTests):
pass
-# FIXME: dont leave commented-out
-# TODO parsing not yet supported
-# class TestParsing(base.BaseParsingTests):
-# pass
+class TestParsing(base.BaseParsingTests):
+ pass
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py
index a10bf6b6aa11a..4cc67986ad065 100644
--- a/pandas/tests/indexes/multi/test_indexing.py
+++ b/pandas/tests/indexes/multi/test_indexing.py
@@ -519,14 +519,15 @@ def test_get_loc_duplicates(self):
result = index.get_loc(2)
expected = slice(0, 4)
assert result == expected
- # FIXME: dont leave commented-out
- # pytest.raises(Exception, index.get_loc, 2)
index = Index(["c", "a", "a", "b", "b"])
rs = index.get_loc("c")
xp = 0
assert rs == xp
+ with pytest.raises(KeyError):
+ index.get_loc(2)
+
def test_get_loc_level(self):
index = MultiIndex(
levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],
diff --git a/pandas/tests/indexes/multi/test_take.py b/pandas/tests/indexes/multi/test_take.py
index 85043ff8812af..f8e7632c91ab2 100644
--- a/pandas/tests/indexes/multi/test_take.py
+++ b/pandas/tests/indexes/multi/test_take.py
@@ -11,9 +11,6 @@ def test_take(idx):
expected = idx[indexer]
assert result.equals(expected)
- # FIXME: Remove Commented Code
- # if not isinstance(idx,
- # (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
# GH 10791
msg = "'MultiIndex' object has no attribute 'freq'"
with pytest.raises(AttributeError, match=msg):
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index 294e3e27c4df5..51a7aa9bb586b 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -809,8 +809,7 @@ def test_range_in_series_indexing(self, size):
@pytest.mark.parametrize(
"slc",
[
- # FIXME: dont leave commented-out
- # pd.IndexSlice[:, :],
+ pd.IndexSlice[:, :],
pd.IndexSlice[:, 1],
pd.IndexSlice[1, :],
pd.IndexSlice[[1], [1]],
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 8c424e07601b8..382d4e611c837 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1130,8 +1130,6 @@ def setup_method(self, load_iris_data):
self.conn.close()
self.conn = self.__engine
self.pandasSQL = sql.SQLDatabase(self.__engine)
- # FIXME: dont leave commented-out
- # super().teardown_method(method)
@pytest.mark.single
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 235aa8e4aa922..f6e0d2f0c1751 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -942,10 +942,8 @@ def test_timedelta64_analytics(self):
s2 = Series(pd.date_range("20120102", periods=3))
expected = Series(s2 - s1)
- # FIXME: don't leave commented-out code
- # this fails as numpy returns timedelta64[us]
- # result = np.abs(s1-s2)
- # assert_frame_equal(result,expected)
+ result = np.abs(s1 - s2)
+ tm.assert_series_equal(result, expected)
result = (s1 - s2).abs()
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index effb324298c95..36a581a8ca492 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1323,18 +1323,22 @@ def test_convert_non_ns(self):
# convert from a numpy array of non-ns datetime64
# note that creating a numpy datetime64 is in LOCAL time!!!!
# seems to work for M8[D], but not for M8[s]
+ # TODO: is the above comment still accurate/needed?
- s = Series(
- np.array(["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]")
+ arr = np.array(
+ ["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]"
)
- tm.assert_series_equal(s, Series(date_range("20130101", periods=3, freq="D")))
-
- # FIXME: dont leave commented-out
- # s = Series(np.array(['2013-01-01 00:00:01','2013-01-01
- # 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]'))
+ ser = Series(arr)
+ expected = Series(date_range("20130101", periods=3, freq="D"))
+ tm.assert_series_equal(ser, expected)
- # tm.assert_series_equal(s,date_range('20130101
- # 00:00:01',period=3,freq='s'))
+ arr = np.array(
+ ["2013-01-01 00:00:01", "2013-01-01 00:00:02", "2013-01-01 00:00:03"],
+ dtype="datetime64[s]",
+ )
+ ser = Series(arr)
+ expected = Series(date_range("20130101 00:00:01", periods=3, freq="s"))
+ tm.assert_series_equal(ser, expected)
@pytest.mark.parametrize(
"index",
| https://api.github.com/repos/pandas-dev/pandas/pulls/33881 | 2020-04-29T22:28:49Z | 2020-04-30T07:04:46Z | 2020-04-30T07:04:46Z | 2020-04-30T19:11:57Z | |
TST/REF: Parametrize consistency data and de-private methods | diff --git a/pandas/tests/window/common.py b/pandas/tests/window/common.py
index 72a0d12edffaf..7a7ab57cdb904 100644
--- a/pandas/tests/window/common.py
+++ b/pandas/tests/window/common.py
@@ -3,7 +3,7 @@
import numpy as np
from numpy.random import randn
-from pandas import DataFrame, Series, bdate_range, notna
+from pandas import DataFrame, Series, bdate_range
import pandas._testing as tm
N, K = 100, 10
@@ -24,155 +24,6 @@ def _create_data(self):
self.frame = DataFrame(randn(N, K), index=self.rng, columns=np.arange(K))
-# create the data only once as we are not setting it
-def _create_consistency_data():
- def create_series():
- return [
- Series(dtype=object),
- Series([np.nan]),
- Series([np.nan, np.nan]),
- Series([3.0]),
- Series([np.nan, 3.0]),
- Series([3.0, np.nan]),
- Series([1.0, 3.0]),
- Series([2.0, 2.0]),
- Series([3.0, 1.0]),
- Series(
- [5.0, 5.0, 5.0, 5.0, np.nan, np.nan, np.nan, 5.0, 5.0, np.nan, np.nan]
- ),
- Series(
- [
- np.nan,
- 5.0,
- 5.0,
- 5.0,
- np.nan,
- np.nan,
- np.nan,
- 5.0,
- 5.0,
- np.nan,
- np.nan,
- ]
- ),
- Series(
- [
- np.nan,
- np.nan,
- 5.0,
- 5.0,
- np.nan,
- np.nan,
- np.nan,
- 5.0,
- 5.0,
- np.nan,
- np.nan,
- ]
- ),
- Series(
- [
- np.nan,
- 3.0,
- np.nan,
- 3.0,
- 4.0,
- 5.0,
- 6.0,
- np.nan,
- np.nan,
- 7.0,
- 12.0,
- 13.0,
- 14.0,
- 15.0,
- ]
- ),
- Series(
- [
- np.nan,
- 5.0,
- np.nan,
- 2.0,
- 4.0,
- 0.0,
- 9.0,
- np.nan,
- np.nan,
- 3.0,
- 12.0,
- 13.0,
- 14.0,
- 15.0,
- ]
- ),
- Series(
- [
- 2.0,
- 3.0,
- np.nan,
- 3.0,
- 4.0,
- 5.0,
- 6.0,
- np.nan,
- np.nan,
- 7.0,
- 12.0,
- 13.0,
- 14.0,
- 15.0,
- ]
- ),
- Series(
- [
- 2.0,
- 5.0,
- np.nan,
- 2.0,
- 4.0,
- 0.0,
- 9.0,
- np.nan,
- np.nan,
- 3.0,
- 12.0,
- 13.0,
- 14.0,
- 15.0,
- ]
- ),
- Series(range(10)),
- Series(range(20, 0, -2)),
- ]
-
- def create_dataframes():
- return [
- DataFrame(),
- DataFrame(columns=["a"]),
- DataFrame(columns=["a", "a"]),
- DataFrame(columns=["a", "b"]),
- DataFrame(np.arange(10).reshape((5, 2))),
- DataFrame(np.arange(25).reshape((5, 5))),
- DataFrame(np.arange(25).reshape((5, 5)), columns=["a", "b", 99, "d", "d"]),
- ] + [DataFrame(s) for s in create_series()]
-
- def is_constant(x):
- values = x.values.ravel()
- return len(set(values[notna(values)])) == 1
-
- def no_nans(x):
- return x.notna().all().all()
-
- # data is a tuple(object, is_constant, no_nans)
- data = create_series() + create_dataframes()
-
- return [(x, is_constant(x), no_nans(x)) for x in data]
-
-
-_consistency_data = _create_consistency_data()
-
-
class ConsistencyBase(Base):
base_functions = [
(lambda v: Series(v).count(), None, "count"),
@@ -210,154 +61,6 @@ class ConsistencyBase(Base):
def _create_data(self):
super()._create_data()
- self.data = _consistency_data
-
- def _test_moments_consistency_mock_mean(self, mean, mock_mean):
- for (x, is_constant, no_nans) in self.data:
- mean_x = mean(x)
- # check that correlation of a series with itself is either 1 or NaN
-
- if mock_mean:
- # check that mean equals mock_mean
- expected = mock_mean(x)
- tm.assert_equal(mean_x, expected.astype("float64"))
-
- def _test_moments_consistency_is_constant(self, min_periods, count, mean, corr):
- for (x, is_constant, no_nans) in self.data:
- count_x = count(x)
- mean_x = mean(x)
- # check that correlation of a series with itself is either 1 or NaN
- corr_x_x = corr(x, x)
-
- if is_constant:
- exp = x.max() if isinstance(x, Series) else x.max().max()
-
- # check mean of constant series
- expected = x * np.nan
- expected[count_x >= max(min_periods, 1)] = exp
- tm.assert_equal(mean_x, expected)
-
- # check correlation of constant series with itself is NaN
- expected[:] = np.nan
- tm.assert_equal(corr_x_x, expected)
-
- def _test_moments_consistency_var_debiasing_factors(
- self, var_biased=None, var_unbiased=None, var_debiasing_factors=None
- ):
- for (x, is_constant, no_nans) in self.data:
- if var_unbiased and var_biased and var_debiasing_factors:
- # check variance debiasing factors
- var_unbiased_x = var_unbiased(x)
- var_biased_x = var_biased(x)
- var_debiasing_factors_x = var_debiasing_factors(x)
- tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)
-
- def _test_moments_consistency_var_data(
- self, min_periods, count, mean, var_unbiased, var_biased
- ):
- for (x, is_constant, no_nans) in self.data:
- count_x = count(x)
- mean_x = mean(x)
- for var in [var_biased, var_unbiased]:
- var_x = var(x)
- assert not (var_x < 0).any().any()
-
- if var is var_biased:
- # check that biased var(x) == mean(x^2) - mean(x)^2
- mean_x2 = mean(x * x)
- tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x))
-
- if is_constant:
- # check that variance of constant series is identically 0
- assert not (var_x > 0).any().any()
- expected = x * np.nan
- expected[count_x >= max(min_periods, 1)] = 0.0
- if var is var_unbiased:
- expected[count_x < 2] = np.nan
- tm.assert_equal(var_x, expected)
-
- def _test_moments_consistency_std_data(
- self, std_unbiased, var_unbiased, std_biased, var_biased
- ):
- for (x, is_constant, no_nans) in self.data:
- for (std, var) in [(std_biased, var_biased), (std_unbiased, var_unbiased)]:
- var_x = var(x)
- std_x = std(x)
- assert not (var_x < 0).any().any()
- assert not (std_x < 0).any().any()
-
- # check that var(x) == std(x)^2
- tm.assert_equal(var_x, std_x * std_x)
-
- def _test_moments_consistency_cov_data(
- self, cov_unbiased, var_unbiased, cov_biased, var_biased
- ):
- for (x, is_constant, no_nans) in self.data:
- for (cov, var) in [(cov_biased, var_biased), (cov_unbiased, var_unbiased)]:
- var_x = var(x)
- assert not (var_x < 0).any().any()
- if cov:
- cov_x_x = cov(x, x)
- assert not (cov_x_x < 0).any().any()
-
- # check that var(x) == cov(x, x)
- tm.assert_equal(var_x, cov_x_x)
-
- def _test_moments_consistency_series_data(
- self,
- corr,
- mean,
- std_biased,
- std_unbiased,
- cov_unbiased,
- var_unbiased,
- var_biased,
- cov_biased,
- ):
- for (x, is_constant, no_nans) in self.data:
- if isinstance(x, Series):
- y = x
- mean_x = mean(x)
- if not x.isna().equals(y.isna()):
- # can only easily test two Series with similar
- # structure
- pass
-
- # check that cor(x, y) is symmetric
- corr_x_y = corr(x, y)
- corr_y_x = corr(y, x)
- tm.assert_equal(corr_x_y, corr_y_x)
-
- for (std, var, cov) in [
- (std_biased, var_biased, cov_biased),
- (std_unbiased, var_unbiased, cov_unbiased),
- ]:
- var_x = var(x)
- std_x = std(x)
-
- if cov:
- # check that cov(x, y) is symmetric
- cov_x_y = cov(x, y)
- cov_y_x = cov(y, x)
- tm.assert_equal(cov_x_y, cov_y_x)
-
- # check that cov(x, y) == (var(x+y) - var(x) -
- # var(y)) / 2
- var_x_plus_y = var(x + y)
- var_y = var(y)
- tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))
-
- # check that corr(x, y) == cov(x, y) / (std(x) *
- # std(y))
- std_y = std(y)
- tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))
-
- if cov is cov_biased:
- # check that biased cov(x, y) == mean(x*y) -
- # mean(x)*mean(y)
- mean_y = mean(y)
- mean_x_times_y = mean(x * y)
- tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))
def _check_pairwise_moment(self, dispatch, name, **kwargs):
def get_result(obj, obj2=None):
@@ -400,3 +103,146 @@ def check_binary_ew_min_periods(name, min_periods, A, B):
Series([1.0]), Series([1.0]), 50, name=name, min_periods=min_periods
)
tm.assert_series_equal(result, Series([np.NaN]))
+
+
+def moments_consistency_mock_mean(x, mean, mock_mean):
+ mean_x = mean(x)
+ # check that correlation of a series with itself is either 1 or NaN
+
+ if mock_mean:
+ # check that mean equals mock_mean
+ expected = mock_mean(x)
+ tm.assert_equal(mean_x, expected.astype("float64"))
+
+
+def moments_consistency_is_constant(x, is_constant, min_periods, count, mean, corr):
+ count_x = count(x)
+ mean_x = mean(x)
+ # check that correlation of a series with itself is either 1 or NaN
+ corr_x_x = corr(x, x)
+
+ if is_constant:
+ exp = x.max() if isinstance(x, Series) else x.max().max()
+
+ # check mean of constant series
+ expected = x * np.nan
+ expected[count_x >= max(min_periods, 1)] = exp
+ tm.assert_equal(mean_x, expected)
+
+ # check correlation of constant series with itself is NaN
+ expected[:] = np.nan
+ tm.assert_equal(corr_x_x, expected)
+
+
+def moments_consistency_var_debiasing_factors(
+ x, var_biased, var_unbiased, var_debiasing_factors
+):
+ if var_unbiased and var_biased and var_debiasing_factors:
+ # check variance debiasing factors
+ var_unbiased_x = var_unbiased(x)
+ var_biased_x = var_biased(x)
+ var_debiasing_factors_x = var_debiasing_factors(x)
+ tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)
+
+
+def moments_consistency_var_data(
+ x, is_constant, min_periods, count, mean, var_unbiased, var_biased
+):
+ count_x = count(x)
+ mean_x = mean(x)
+ for var in [var_biased, var_unbiased]:
+ var_x = var(x)
+ assert not (var_x < 0).any().any()
+
+ if var is var_biased:
+ # check that biased var(x) == mean(x^2) - mean(x)^2
+ mean_x2 = mean(x * x)
+ tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x))
+
+ if is_constant:
+ # check that variance of constant series is identically 0
+ assert not (var_x > 0).any().any()
+ expected = x * np.nan
+ expected[count_x >= max(min_periods, 1)] = 0.0
+ if var is var_unbiased:
+ expected[count_x < 2] = np.nan
+ tm.assert_equal(var_x, expected)
+
+
+def moments_consistency_std_data(x, std_unbiased, var_unbiased, std_biased, var_biased):
+ for (std, var) in [(std_biased, var_biased), (std_unbiased, var_unbiased)]:
+ var_x = var(x)
+ std_x = std(x)
+ assert not (var_x < 0).any().any()
+ assert not (std_x < 0).any().any()
+
+ # check that var(x) == std(x)^2
+ tm.assert_equal(var_x, std_x * std_x)
+
+
+def moments_consistency_cov_data(x, cov_unbiased, var_unbiased, cov_biased, var_biased):
+ for (cov, var) in [(cov_biased, var_biased), (cov_unbiased, var_unbiased)]:
+ var_x = var(x)
+ assert not (var_x < 0).any().any()
+ if cov:
+ cov_x_x = cov(x, x)
+ assert not (cov_x_x < 0).any().any()
+
+ # check that var(x) == cov(x, x)
+ tm.assert_equal(var_x, cov_x_x)
+
+
+def moments_consistency_series_data(
+ x,
+ corr,
+ mean,
+ std_biased,
+ std_unbiased,
+ cov_unbiased,
+ var_unbiased,
+ var_biased,
+ cov_biased,
+):
+ if isinstance(x, Series):
+ y = x
+ mean_x = mean(x)
+ if not x.isna().equals(y.isna()):
+ # can only easily test two Series with similar
+ # structure
+ pass
+
+ # check that cor(x, y) is symmetric
+ corr_x_y = corr(x, y)
+ corr_y_x = corr(y, x)
+ tm.assert_equal(corr_x_y, corr_y_x)
+
+ for (std, var, cov) in [
+ (std_biased, var_biased, cov_biased),
+ (std_unbiased, var_unbiased, cov_unbiased),
+ ]:
+ var_x = var(x)
+ std_x = std(x)
+
+ if cov:
+ # check that cov(x, y) is symmetric
+ cov_x_y = cov(x, y)
+ cov_y_x = cov(y, x)
+ tm.assert_equal(cov_x_y, cov_y_x)
+
+ # check that cov(x, y) == (var(x+y) - var(x) -
+ # var(y)) / 2
+ var_x_plus_y = var(x + y)
+ var_y = var(y)
+ tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))
+
+ # check that corr(x, y) == cov(x, y) / (std(x) *
+ # std(y))
+ std_y = std(y)
+ tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))
+
+ if cov is cov_biased:
+ # check that biased cov(x, y) == mean(x*y) -
+ # mean(x)*mean(y)
+ mean_y = mean(y)
+ mean_x_times_y = mean(x * y)
+ tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))
diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index fb46ca51ace58..856c8f3884816 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -1,7 +1,10 @@
+import numpy as np
import pytest
import pandas.util._test_decorators as td
+from pandas import DataFrame, Series, notna
+
@pytest.fixture(params=[True, False])
def raw(request):
@@ -87,3 +90,155 @@ def engine(request):
def engine_and_raw(request):
"""engine and raw keyword arguments for rolling.apply"""
return request.param
+
+
+# create the data only once as we are not setting it
+def _create_consistency_data():
+ def create_series():
+ return [
+ Series(dtype=object),
+ Series([np.nan]),
+ Series([np.nan, np.nan]),
+ Series([3.0]),
+ Series([np.nan, 3.0]),
+ Series([3.0, np.nan]),
+ Series([1.0, 3.0]),
+ Series([2.0, 2.0]),
+ Series([3.0, 1.0]),
+ Series(
+ [5.0, 5.0, 5.0, 5.0, np.nan, np.nan, np.nan, 5.0, 5.0, np.nan, np.nan]
+ ),
+ Series(
+ [
+ np.nan,
+ 5.0,
+ 5.0,
+ 5.0,
+ np.nan,
+ np.nan,
+ np.nan,
+ 5.0,
+ 5.0,
+ np.nan,
+ np.nan,
+ ]
+ ),
+ Series(
+ [
+ np.nan,
+ np.nan,
+ 5.0,
+ 5.0,
+ np.nan,
+ np.nan,
+ np.nan,
+ 5.0,
+ 5.0,
+ np.nan,
+ np.nan,
+ ]
+ ),
+ Series(
+ [
+ np.nan,
+ 3.0,
+ np.nan,
+ 3.0,
+ 4.0,
+ 5.0,
+ 6.0,
+ np.nan,
+ np.nan,
+ 7.0,
+ 12.0,
+ 13.0,
+ 14.0,
+ 15.0,
+ ]
+ ),
+ Series(
+ [
+ np.nan,
+ 5.0,
+ np.nan,
+ 2.0,
+ 4.0,
+ 0.0,
+ 9.0,
+ np.nan,
+ np.nan,
+ 3.0,
+ 12.0,
+ 13.0,
+ 14.0,
+ 15.0,
+ ]
+ ),
+ Series(
+ [
+ 2.0,
+ 3.0,
+ np.nan,
+ 3.0,
+ 4.0,
+ 5.0,
+ 6.0,
+ np.nan,
+ np.nan,
+ 7.0,
+ 12.0,
+ 13.0,
+ 14.0,
+ 15.0,
+ ]
+ ),
+ Series(
+ [
+ 2.0,
+ 5.0,
+ np.nan,
+ 2.0,
+ 4.0,
+ 0.0,
+ 9.0,
+ np.nan,
+ np.nan,
+ 3.0,
+ 12.0,
+ 13.0,
+ 14.0,
+ 15.0,
+ ]
+ ),
+ Series(range(10)),
+ Series(range(20, 0, -2)),
+ ]
+
+ def create_dataframes():
+ return [
+ DataFrame(),
+ DataFrame(columns=["a"]),
+ DataFrame(columns=["a", "a"]),
+ DataFrame(columns=["a", "b"]),
+ DataFrame(np.arange(10).reshape((5, 2))),
+ DataFrame(np.arange(25).reshape((5, 5))),
+ DataFrame(np.arange(25).reshape((5, 5)), columns=["a", "b", 99, "d", "d"]),
+ ] + [DataFrame(s) for s in create_series()]
+
+ def is_constant(x):
+ values = x.values.ravel()
+ return len(set(values[notna(values)])) == 1
+
+ def no_nans(x):
+ return x.notna().all().all()
+
+ # data is a tuple(object, is_constant, no_nans)
+ data = create_series() + create_dataframes()
+
+ return [(x, is_constant(x), no_nans(x)) for x in data]
+
+
+@pytest.fixture(params=_create_consistency_data())
+def consistency_data(request):
+ """Create consistency data"""
+ return request.param
diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py
index 78b086927adfb..37048265253f7 100644
--- a/pandas/tests/window/moments/test_moments_ewm.py
+++ b/pandas/tests/window/moments/test_moments_ewm.py
@@ -11,6 +11,13 @@
check_binary_ew,
check_binary_ew_min_periods,
ew_func,
+ moments_consistency_cov_data,
+ moments_consistency_is_constant,
+ moments_consistency_mock_mean,
+ moments_consistency_series_data,
+ moments_consistency_std_data,
+ moments_consistency_var_data,
+ moments_consistency_var_debiasing_factors,
)
@@ -293,227 +300,240 @@ def test_different_input_array_raise_exception(self, name, binary_ew_data):
with pytest.raises(Exception, match=msg):
ew_func(A, randn(50), 20, name=name, min_periods=5)
- @pytest.mark.slow
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- @pytest.mark.parametrize("adjust", [True, False])
- @pytest.mark.parametrize("ignore_na", [True, False])
- def test_ewm_consistency(self, min_periods, adjust, ignore_na):
- def _weights(s, com, adjust, ignore_na):
- if isinstance(s, DataFrame):
- if not len(s.columns):
- return DataFrame(index=s.index, columns=s.columns)
- w = concat(
- [
- _weights(
- s.iloc[:, i], com=com, adjust=adjust, ignore_na=ignore_na
- )
- for i, _ in enumerate(s.columns)
- ],
- axis=1,
- )
- w.index = s.index
- w.columns = s.columns
- return w
-
- w = Series(np.nan, index=s.index)
- alpha = 1.0 / (1.0 + com)
- if ignore_na:
- w[s.notna()] = _weights(
- s[s.notna()], com=com, adjust=adjust, ignore_na=False
- )
- elif adjust:
- for i in range(len(s)):
- if s.iat[i] == s.iat[i]:
- w.iat[i] = pow(1.0 / (1.0 - alpha), i)
- else:
- sum_wts = 0.0
- prev_i = -1
- for i in range(len(s)):
- if s.iat[i] == s.iat[i]:
- if prev_i == -1:
- w.iat[i] = 1.0
- else:
- w.iat[i] = alpha * sum_wts / pow(1.0 - alpha, i - prev_i)
- sum_wts += w.iat[i]
- prev_i = i
+
+@pytest.mark.slow
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("adjust", [True, False])
+@pytest.mark.parametrize("ignore_na", [True, False])
+def test_ewm_consistency(consistency_data, min_periods, adjust, ignore_na):
+ def _weights(s, com, adjust, ignore_na):
+ if isinstance(s, DataFrame):
+ if not len(s.columns):
+ return DataFrame(index=s.index, columns=s.columns)
+ w = concat(
+ [
+ _weights(s.iloc[:, i], com=com, adjust=adjust, ignore_na=ignore_na)
+ for i, _ in enumerate(s.columns)
+ ],
+ axis=1,
+ )
+ w.index = s.index
+ w.columns = s.columns
return w
- def _variance_debiasing_factors(s, com, adjust, ignore_na):
- weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
- cum_sum = weights.cumsum().fillna(method="ffill")
- cum_sum_sq = (weights * weights).cumsum().fillna(method="ffill")
- numerator = cum_sum * cum_sum
- denominator = numerator - cum_sum_sq
- denominator[denominator <= 0.0] = np.nan
- return numerator / denominator
-
- def _ewma(s, com, min_periods, adjust, ignore_na):
- weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
- result = (
- s.multiply(weights)
- .cumsum()
- .divide(weights.cumsum())
- .fillna(method="ffill")
+ w = Series(np.nan, index=s.index)
+ alpha = 1.0 / (1.0 + com)
+ if ignore_na:
+ w[s.notna()] = _weights(
+ s[s.notna()], com=com, adjust=adjust, ignore_na=False
)
- result[
- s.expanding().count() < (max(min_periods, 1) if min_periods else 1)
- ] = np.nan
- return result
-
- com = 3.0
- self._test_moments_consistency_mock_mean(
- mean=lambda x: x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).mean(),
- mock_mean=lambda x: _ewma(
- x, com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ),
+ elif adjust:
+ for i in range(len(s)):
+ if s.iat[i] == s.iat[i]:
+ w.iat[i] = pow(1.0 / (1.0 - alpha), i)
+ else:
+ sum_wts = 0.0
+ prev_i = -1
+ for i in range(len(s)):
+ if s.iat[i] == s.iat[i]:
+ if prev_i == -1:
+ w.iat[i] = 1.0
+ else:
+ w.iat[i] = alpha * sum_wts / pow(1.0 - alpha, i - prev_i)
+ sum_wts += w.iat[i]
+ prev_i = i
+ return w
+
+ def _variance_debiasing_factors(s, com, adjust, ignore_na):
+ weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
+ cum_sum = weights.cumsum().fillna(method="ffill")
+ cum_sum_sq = (weights * weights).cumsum().fillna(method="ffill")
+ numerator = cum_sum * cum_sum
+ denominator = numerator - cum_sum_sq
+ denominator[denominator <= 0.0] = np.nan
+ return numerator / denominator
+
+ def _ewma(s, com, min_periods, adjust, ignore_na):
+ weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
+ result = (
+ s.multiply(weights).cumsum().divide(weights.cumsum()).fillna(method="ffill")
)
-
- self._test_moments_consistency_is_constant(
- min_periods=min_periods,
- count=lambda x: x.expanding().count(),
- mean=lambda x: x.ewm(
+ result[
+ s.expanding().count() < (max(min_periods, 1) if min_periods else 1)
+ ] = np.nan
+ return result
+
+ x, is_constant, no_nans = consistency_data
+ com = 3.0
+ moments_consistency_mock_mean(
+ x=x,
+ mean=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).mean(),
+ mock_mean=lambda x: _ewma(
+ x, com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ),
+ )
+
+ moments_consistency_is_constant(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: x.expanding().count(),
+ mean=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).mean(),
+ corr=lambda x, y: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).corr(y),
+ )
+
+ moments_consistency_var_debiasing_factors(
+ x=x,
+ var_unbiased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).mean(),
- corr=lambda x, y: x.ewm(
+ ).var(bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).corr(y),
- )
-
- self._test_moments_consistency_var_debiasing_factors(
- var_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=False)
- ),
- var_biased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=True)
- ),
- var_debiasing_factors=lambda x: (
- _variance_debiasing_factors(
- x, com=com, adjust=adjust, ignore_na=ignore_na
- )
- ),
- )
-
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- @pytest.mark.parametrize("adjust", [True, False])
- @pytest.mark.parametrize("ignore_na", [True, False])
- def test_ewm_consistency_var(self, min_periods, adjust, ignore_na):
- com = 3.0
- self._test_moments_consistency_var_data(
- min_periods,
- count=lambda x: x.expanding().count(),
- mean=lambda x: x.ewm(
+ ).var(bias=True)
+ ),
+ var_debiasing_factors=lambda x: (
+ _variance_debiasing_factors(x, com=com, adjust=adjust, ignore_na=ignore_na)
+ ),
+ )
+
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("adjust", [True, False])
+@pytest.mark.parametrize("ignore_na", [True, False])
+def test_ewm_consistency_var(consistency_data, min_periods, adjust, ignore_na):
+ x, is_constant, no_nans = consistency_data
+ com = 3.0
+ moments_consistency_var_data(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: x.expanding().count(),
+ mean=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).mean(),
+ var_unbiased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).mean(),
- var_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=False)
- ),
- var_biased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=True)
- ),
- )
-
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- @pytest.mark.parametrize("adjust", [True, False])
- @pytest.mark.parametrize("ignore_na", [True, False])
- def test_ewm_consistency_std(self, min_periods, adjust, ignore_na):
- com = 3.0
- self._test_moments_consistency_std_data(
- var_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=False)
- ),
- std_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).std(bias=False)
- ),
- var_biased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=True)
- ),
- std_biased=lambda x: x.ewm(
+ ).var(bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).std(bias=True),
- )
-
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- @pytest.mark.parametrize("adjust", [True, False])
- @pytest.mark.parametrize("ignore_na", [True, False])
- def test_ewm_consistency_cov(self, min_periods, adjust, ignore_na):
- com = 3.0
- self._test_moments_consistency_cov_data(
- var_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=False)
- ),
- cov_unbiased=lambda x, y: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).cov(y, bias=False)
- ),
- var_biased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=True)
- ),
- cov_biased=lambda x, y: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).cov(y, bias=True)
- ),
- )
-
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- @pytest.mark.parametrize("adjust", [True, False])
- @pytest.mark.parametrize("ignore_na", [True, False])
- def test_ewm_consistency_series_data(self, min_periods, adjust, ignore_na):
- com = 3.0
- self._test_moments_consistency_series_data(
- mean=lambda x: x.ewm(
+ ).var(bias=True)
+ ),
+ )
+
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("adjust", [True, False])
+@pytest.mark.parametrize("ignore_na", [True, False])
+def test_ewm_consistency_std(consistency_data, min_periods, adjust, ignore_na):
+ x, is_constant, no_nans = consistency_data
+ com = 3.0
+ moments_consistency_std_data(
+ x=x,
+ var_unbiased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).mean(),
- corr=lambda x, y: x.ewm(
+ ).var(bias=False)
+ ),
+ std_unbiased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).corr(y),
- var_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=False)
- ),
- std_unbiased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).std(bias=False)
- ),
- cov_unbiased=lambda x, y: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).cov(y, bias=False)
- ),
- var_biased=lambda x: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).var(bias=True)
- ),
- std_biased=lambda x: x.ewm(
+ ).std(bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).std(bias=True),
- cov_biased=lambda x, y: (
- x.ewm(
- com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
- ).cov(y, bias=True)
- ),
- )
+ ).var(bias=True)
+ ),
+ std_biased=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).std(bias=True),
+ )
+
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("adjust", [True, False])
+@pytest.mark.parametrize("ignore_na", [True, False])
+def test_ewm_consistency_cov(consistency_data, min_periods, adjust, ignore_na):
+ x, is_constant, no_nans = consistency_data
+ com = 3.0
+ moments_consistency_cov_data(
+ x=x,
+ var_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=False)
+ ),
+ cov_unbiased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=True)
+ ),
+ cov_biased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=True)
+ ),
+ )
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("adjust", [True, False])
+@pytest.mark.parametrize("ignore_na", [True, False])
+def test_ewm_consistency_series_data(consistency_data, min_periods, adjust, ignore_na):
+ x, is_constant, no_nans = consistency_data
+ com = 3.0
+ moments_consistency_series_data(
+ x=x,
+ mean=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).mean(),
+ corr=lambda x, y: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).corr(y),
+ var_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=False)
+ ),
+ std_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).std(bias=False)
+ ),
+ cov_unbiased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=True)
+ ),
+ std_biased=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).std(bias=True),
+ cov_biased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=True)
+ ),
+ )
diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py
index a358f0e7057f3..e97383823f00d 100644
--- a/pandas/tests/window/moments/test_moments_expanding.py
+++ b/pandas/tests/window/moments/test_moments_expanding.py
@@ -6,7 +6,16 @@
from pandas import DataFrame, Index, MultiIndex, Series, isna, notna
import pandas._testing as tm
-from pandas.tests.window.common import ConsistencyBase
+from pandas.tests.window.common import (
+ ConsistencyBase,
+ moments_consistency_cov_data,
+ moments_consistency_is_constant,
+ moments_consistency_mock_mean,
+ moments_consistency_series_data,
+ moments_consistency_std_data,
+ moments_consistency_var_data,
+ moments_consistency_var_debiasing_factors,
+)
class TestExpandingMomentsConsistency(ConsistencyBase):
@@ -334,8 +343,8 @@ def test_moment_functions_zero_length_pairwise(self, f):
@pytest.mark.slow
@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_consistency(self, min_periods):
-
+ def test_expanding_consistency(self, consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
# suppress warnings about empty slices, as we are deliberately testing
# with empty/0-length Series/DataFrames
with warnings.catch_warnings():
@@ -346,20 +355,24 @@ def test_expanding_consistency(self, min_periods):
)
# test consistency between different expanding_* moments
- self._test_moments_consistency_mock_mean(
+ moments_consistency_mock_mean(
+ x=x,
mean=lambda x: x.expanding(min_periods=min_periods).mean(),
mock_mean=lambda x: x.expanding(min_periods=min_periods).sum()
/ x.expanding().count(),
)
- self._test_moments_consistency_is_constant(
+ moments_consistency_is_constant(
+ x=x,
+ is_constant=is_constant,
min_periods=min_periods,
count=lambda x: x.expanding().count(),
mean=lambda x: x.expanding(min_periods=min_periods).mean(),
corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
)
- self._test_moments_consistency_var_debiasing_factors(
+ moments_consistency_var_debiasing_factors(
+ x=x,
var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
var_debiasing_factors=lambda x: (
@@ -369,7 +382,8 @@ def test_expanding_consistency(self, min_periods):
)
@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_apply_consistency(self, min_periods):
+ def test_expanding_apply_consistency(self, consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
@@ -379,77 +393,89 @@ def test_expanding_apply_consistency(self, min_periods):
# test consistency between expanding_xyz() and either (a)
# expanding_apply of Series.xyz(), or (b) expanding_apply of
# np.nanxyz()
- for (x, is_constant, no_nans) in self.data:
- functions = self.base_functions
-
- # GH 8269
- if no_nans:
- functions = self.base_functions + self.no_nan_functions
- for (f, require_min_periods, name) in functions:
- expanding_f = getattr(x.expanding(min_periods=min_periods), name)
-
- if (
- require_min_periods
- and (min_periods is not None)
- and (min_periods < require_min_periods)
- ):
- continue
-
- if name == "count":
- expanding_f_result = expanding_f()
- expanding_apply_f_result = x.expanding(min_periods=0).apply(
- func=f, raw=True
- )
+ functions = self.base_functions
+
+ # GH 8269
+ if no_nans:
+ functions = self.base_functions + self.no_nan_functions
+ for (f, require_min_periods, name) in functions:
+ expanding_f = getattr(x.expanding(min_periods=min_periods), name)
+
+ if (
+ require_min_periods
+ and (min_periods is not None)
+ and (min_periods < require_min_periods)
+ ):
+ continue
+
+ if name == "count":
+ expanding_f_result = expanding_f()
+ expanding_apply_f_result = x.expanding(min_periods=0).apply(
+ func=f, raw=True
+ )
+ else:
+ if name in ["cov", "corr"]:
+ expanding_f_result = expanding_f(pairwise=False)
else:
- if name in ["cov", "corr"]:
- expanding_f_result = expanding_f(pairwise=False)
- else:
- expanding_f_result = expanding_f()
- expanding_apply_f_result = x.expanding(
- min_periods=min_periods
- ).apply(func=f, raw=True)
-
- # GH 9422
- if name in ["sum", "prod"]:
- tm.assert_equal(expanding_f_result, expanding_apply_f_result)
+ expanding_f_result = expanding_f()
+ expanding_apply_f_result = x.expanding(
+ min_periods=min_periods
+ ).apply(func=f, raw=True)
+
+ # GH 9422
+ if name in ["sum", "prod"]:
+ tm.assert_equal(expanding_f_result, expanding_apply_f_result)
+
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_moments_consistency_var(consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_var_data(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: x.expanding(min_periods=min_periods).count(),
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ )
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_moments_consistency_var(self, min_periods):
- self._test_moments_consistency_var_data(
- min_periods=min_periods,
- count=lambda x: x.expanding(min_periods=min_periods).count(),
- mean=lambda x: x.expanding(min_periods=min_periods).mean(),
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- )
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_consistency_std(self, min_periods):
- self._test_moments_consistency_std_data(
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
- )
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_expanding_consistency_std(consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_std_data(
+ x=x,
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
+ )
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_consistency_cov(self, min_periods):
- self._test_moments_consistency_cov_data(
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
- )
- @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
- def test_expanding_consistency_series(self, min_periods):
- self._test_moments_consistency_series_data(
- mean=lambda x: x.expanding(min_periods=min_periods).mean(),
- corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
- cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
- cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
- )
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_expanding_consistency_cov(consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_cov_data(
+ x=x,
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
+ )
+
+
+@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+def test_expanding_consistency_series(consistency_data, min_periods):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_series_data(
+ x=x,
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
+ cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
+ cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
+ )
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index 503f2e12bea03..c15b7ed00b9e3 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -12,7 +12,17 @@
from pandas import DataFrame, DatetimeIndex, Index, Series, isna, notna
import pandas._testing as tm
from pandas.core.window.common import _flex_binary_moment
-from pandas.tests.window.common import Base, ConsistencyBase
+from pandas.tests.window.common import (
+ Base,
+ ConsistencyBase,
+ moments_consistency_cov_data,
+ moments_consistency_is_constant,
+ moments_consistency_mock_mean,
+ moments_consistency_series_data,
+ moments_consistency_std_data,
+ moments_consistency_var_data,
+ moments_consistency_var_debiasing_factors,
+)
import pandas.tseries.offsets as offsets
@@ -936,88 +946,13 @@ class TestRollingMomentsConsistency(ConsistencyBase):
def setup_method(self, method):
self._create_data()
- @pytest.mark.slow
@pytest.mark.parametrize(
"window,min_periods,center", list(_rolling_consistency_cases())
)
- def test_rolling_consistency(self, window, min_periods, center):
-
- # suppress warnings about empty slices, as we are deliberately testing
- # with empty/0-length Series/DataFrames
- with warnings.catch_warnings():
- warnings.filterwarnings(
- "ignore",
- message=".*(empty slice|0 for slice).*",
- category=RuntimeWarning,
- )
-
- # test consistency between different rolling_* moments
- self._test_moments_consistency_mock_mean(
- mean=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).mean()
- ),
- mock_mean=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center)
- .sum()
- .divide(
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).count()
- )
- ),
- )
-
- self._test_moments_consistency_is_constant(
- min_periods=min_periods,
- count=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).count()
- ),
- mean=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).mean()
- ),
- corr=lambda x, y: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).corr(y)
- ),
- )
-
- self._test_moments_consistency_var_debiasing_factors(
- var_unbiased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).var()
- ),
- var_biased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).var(ddof=0)
- ),
- var_debiasing_factors=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center)
- .count()
- .divide(
- (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).count()
- - 1.0
- ).replace(0.0, np.nan)
- )
- ),
- )
-
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_apply_consistency(self, window, min_periods, center):
-
+ def test_rolling_apply_consistency(
+ self, consistency_data, window, min_periods, center
+ ):
+ x, is_constant, no_nans = consistency_data
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
@@ -1027,149 +962,41 @@ def test_rolling_apply_consistency(self, window, min_periods, center):
# test consistency between rolling_xyz() and either (a)
# rolling_apply of Series.xyz(), or (b) rolling_apply of
# np.nanxyz()
- for (x, is_constant, no_nans) in self.data:
- functions = self.base_functions
-
- # GH 8269
- if no_nans:
- functions = self.base_functions + self.no_nan_functions
- for (f, require_min_periods, name) in functions:
- rolling_f = getattr(
- x.rolling(
- window=window, center=center, min_periods=min_periods
- ),
- name,
- )
-
- if (
- require_min_periods
- and (min_periods is not None)
- and (min_periods < require_min_periods)
- ):
- continue
-
- if name == "count":
- rolling_f_result = rolling_f()
- rolling_apply_f_result = x.rolling(
- window=window, min_periods=min_periods, center=center
- ).apply(func=f, raw=True)
- else:
- if name in ["cov", "corr"]:
- rolling_f_result = rolling_f(pairwise=False)
- else:
- rolling_f_result = rolling_f()
- rolling_apply_f_result = x.rolling(
- window=window, min_periods=min_periods, center=center
- ).apply(func=f, raw=True)
-
- # GH 9422
- if name in ["sum", "prod"]:
- tm.assert_equal(rolling_f_result, rolling_apply_f_result)
-
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_consistency_var(self, window, min_periods, center):
- self._test_moments_consistency_var_data(
- min_periods,
- count=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).count()
- ),
- mean=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).mean()
- ),
- var_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var()
- ),
- var_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var(
- ddof=0
+ functions = self.base_functions
+
+ # GH 8269
+ if no_nans:
+ functions = self.base_functions + self.no_nan_functions
+ for (f, require_min_periods, name) in functions:
+ rolling_f = getattr(
+ x.rolling(window=window, center=center, min_periods=min_periods),
+ name,
)
- ),
- )
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_consistency_std(self, window, min_periods, center):
- self._test_moments_consistency_std_data(
- var_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var()
- ),
- std_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).std()
- ),
- var_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var(
- ddof=0
- )
- ),
- std_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).std(
- ddof=0
- )
- ),
- )
+ if (
+ require_min_periods
+ and (min_periods is not None)
+ and (min_periods < require_min_periods)
+ ):
+ continue
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_consistency_cov(self, window, min_periods, center):
- self._test_moments_consistency_cov_data(
- var_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var()
- ),
- cov_unbiased=lambda x, y: (
- x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
- ),
- var_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var(
- ddof=0
- )
- ),
- cov_biased=lambda x, y: (
- x.rolling(window=window, min_periods=min_periods, center=center).cov(
- y, ddof=0
- )
- ),
- )
+ if name == "count":
+ rolling_f_result = rolling_f()
+ rolling_apply_f_result = x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).apply(func=f, raw=True)
+ else:
+ if name in ["cov", "corr"]:
+ rolling_f_result = rolling_f(pairwise=False)
+ else:
+ rolling_f_result = rolling_f()
+ rolling_apply_f_result = x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).apply(func=f, raw=True)
- @pytest.mark.parametrize(
- "window,min_periods,center", list(_rolling_consistency_cases())
- )
- def test_rolling_consistency_series(self, window, min_periods, center):
- self._test_moments_consistency_series_data(
- mean=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).mean()
- ),
- corr=lambda x, y: (
- x.rolling(window=window, min_periods=min_periods, center=center).corr(y)
- ),
- var_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var()
- ),
- std_unbiased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).std()
- ),
- cov_unbiased=lambda x, y: (
- x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
- ),
- var_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).var(
- ddof=0
- )
- ),
- std_biased=lambda x: (
- x.rolling(window=window, min_periods=min_periods, center=center).std(
- ddof=0
- )
- ),
- cov_biased=lambda x, y: (
- x.rolling(window=window, min_periods=min_periods, center=center).cov(
- y, ddof=0
- )
- ),
- )
+ # GH 9422
+ if name in ["sum", "prod"]:
+ tm.assert_equal(rolling_f_result, rolling_apply_f_result)
# binary moments
def test_rolling_cov(self):
@@ -1601,3 +1428,180 @@ def test_moment_functions_zero_length_pairwise(self):
df2_result = f(df2)
tm.assert_frame_equal(df2_result, df2_expected)
+
+
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_consistency_var(consistency_data, window, min_periods, center):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_var_data(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).count()
+ ),
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(ddof=0)
+ ),
+ )
+
+
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_consistency_std(consistency_data, window, min_periods, center):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_std_data(
+ x=x,
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ std_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std()
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(ddof=0)
+ ),
+ std_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std(ddof=0)
+ ),
+ )
+
+
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_consistency_cov(consistency_data, window, min_periods, center):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_cov_data(
+ x=x,
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ cov_unbiased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(ddof=0)
+ ),
+ cov_biased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(
+ y, ddof=0
+ )
+ ),
+ )
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_consistency_series(consistency_data, window, min_periods, center):
+ x, is_constant, no_nans = consistency_data
+ moments_consistency_series_data(
+ x=x,
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ corr=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).corr(y)
+ ),
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ std_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std()
+ ),
+ cov_unbiased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(ddof=0)
+ ),
+ std_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std(ddof=0)
+ ),
+ cov_biased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(
+ y, ddof=0
+ )
+ ),
+ )
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+)
+def test_rolling_consistency(consistency_data, window, min_periods, center):
+ x, is_constant, no_nans = consistency_data
+ # suppress warnings about empty slices, as we are deliberately testing
+ # with empty/0-length Series/DataFrames
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
+ )
+
+ # test consistency between different rolling_* moments
+ moments_consistency_mock_mean(
+ x=x,
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ mock_mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center)
+ .sum()
+ .divide(
+ x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).count()
+ )
+ ),
+ )
+
+ moments_consistency_is_constant(
+ x=x,
+ is_constant=is_constant,
+ min_periods=min_periods,
+ count=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).count()
+ ),
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ corr=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).corr(y)
+ ),
+ )
+
+ moments_consistency_var_debiasing_factors(
+ x=x,
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(
+ ddof=0
+ )
+ ),
+ var_debiasing_factors=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center)
+ .count()
+ .divide(
+ (
+ x.rolling(
+ window=window, min_periods=min_periods, center=center
+ ).count()
+ - 1.0
+ ).replace(0.0, np.nan)
+ )
+ ),
+ )
| xref #30486
I am sorry that this PR looks huge again. @jreback
But this seems a bit unavoidable, and please allow me to briefly explain this, and it is quite simple actually:
1. move `_create_consistency_data` method to `conftest.py` and fixturize it as `consistency_data`.
2. Use `consistency_data` as fixture, and parametrize it to replace the inner loops.
3. Now since consistency_data is fixture, we do not need `self.data = _create_consistency_data()` as part init in `ConsistencyBase`, so I remove it, also a bunch of tests can be moved out of the BIG ConsistencyBase class (which I think is the ultimate goal: avoid using big classes, but simply the functions).
4. I also move some tests in `test_moments_rolling`, `test_moments_ewm`, and `test_moment_expanding` out of their classes to be independent test functions
After this PR, we could start reducing the reliance on the giant Base/ConsistencyBase classes, and next step will be fixturize other data and then reduce more reliance on those classes and make tests look smaller.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33875 | 2020-04-29T18:04:43Z | 2020-04-30T17:48:05Z | 2020-04-30T17:48:05Z | 2020-04-30T17:48:38Z |
TST: Fix xfailed offset test | diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py
index 082aa45f959ff..81465e733da85 100644
--- a/pandas/tests/tseries/offsets/test_offsets_properties.py
+++ b/pandas/tests/tseries/offsets/test_offsets_properties.py
@@ -123,11 +123,12 @@ def test_apply_index_implementations(offset, rng):
# TODO: Check randomly assorted entries, not just first/last
-@pytest.mark.xfail # TODO: reason?
@given(gen_yqm_offset)
def test_shift_across_dst(offset):
# GH#18319 check that 1) timezone is correctly normalized and
# 2) that hour is not incorrectly changed by this normalization
+ assume(not offset.normalize)
+
# Note that dti includes a transition across DST boundary
dti = pd.date_range(
start="2017-10-30 12:00:00", end="2017-11-06", freq="D", tz="US/Eastern"
| - [ ] 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/33874 | 2020-04-29T18:00:01Z | 2020-04-29T22:31:21Z | 2020-04-29T22:31:21Z | 2020-04-29T22:32:35Z |
TST: parametrize test_partial_slicing tests | diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py
index 028a713a8af81..635470b930252 100644
--- a/pandas/tests/indexes/datetimes/test_partial_slicing.py
+++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py
@@ -6,7 +6,6 @@
import numpy as np
import pytest
-import pandas as pd
from pandas import (
DataFrame,
DatetimeIndex,
@@ -21,51 +20,12 @@
class TestSlicing:
- def test_slice_with_negative_step(self):
- ts = Series(np.arange(20), date_range("2014-01-01", periods=20, freq="MS"))
- SLC = pd.IndexSlice
-
- def assert_slices_equivalent(l_slc, i_slc):
- expected = ts.iloc[i_slc]
-
- tm.assert_series_equal(ts[l_slc], expected)
- tm.assert_series_equal(ts.loc[l_slc], expected)
- tm.assert_series_equal(ts.loc[l_slc], expected)
-
- assert_slices_equivalent(SLC[Timestamp("2014-10-01") :: -1], SLC[9::-1])
- assert_slices_equivalent(SLC["2014-10-01"::-1], SLC[9::-1])
-
- assert_slices_equivalent(SLC[: Timestamp("2014-10-01") : -1], SLC[:8:-1])
- assert_slices_equivalent(SLC[:"2014-10-01":-1], SLC[:8:-1])
-
- assert_slices_equivalent(SLC["2015-02-01":"2014-10-01":-1], SLC[13:8:-1])
- assert_slices_equivalent(
- SLC[Timestamp("2015-02-01") : Timestamp("2014-10-01") : -1], SLC[13:8:-1]
- )
- assert_slices_equivalent(
- SLC["2015-02-01" : Timestamp("2014-10-01") : -1], SLC[13:8:-1]
- )
- assert_slices_equivalent(
- SLC[Timestamp("2015-02-01") : "2014-10-01" : -1], SLC[13:8:-1]
- )
-
- assert_slices_equivalent(SLC["2014-10-01":"2015-02-01":-1], SLC[0:0:-1])
-
- def test_slice_with_zero_step_raises(self):
- ts = Series(np.arange(20), date_range("2014-01-01", periods=20, freq="MS"))
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
-
def test_monotone_DTI_indexing_bug(self):
# GH 19362
# Testing accessing the first element in a monotonic descending
# partial string indexing.
- df = pd.DataFrame(list(range(5)))
+ df = DataFrame(list(range(5)))
date_list = [
"2018-01-02",
"2017-02-10",
@@ -73,17 +33,13 @@ def test_monotone_DTI_indexing_bug(self):
"2015-03-15",
"2014-03-16",
]
- date_index = pd.to_datetime(date_list)
+ date_index = DatetimeIndex(date_list)
df["date"] = date_index
- expected = pd.DataFrame({0: list(range(5)), "date": date_index})
+ expected = DataFrame({0: list(range(5)), "date": date_index})
tm.assert_frame_equal(df, expected)
- df = pd.DataFrame(
- {"A": [1, 2, 3]}, index=pd.date_range("20170101", periods=3)[::-1]
- )
- expected = pd.DataFrame(
- {"A": 1}, index=pd.date_range("20170103", periods=1)[::-1]
- )
+ df = DataFrame({"A": [1, 2, 3]}, index=date_range("20170101", periods=3)[::-1])
+ expected = DataFrame({"A": 1}, index=date_range("20170103", periods=1)[::-1])
tm.assert_frame_equal(df.loc["2017-01-03"], expected)
def test_slice_year(self):
@@ -120,7 +76,7 @@ def test_slice_end_of_period_resolution(self, partial_dtime):
# GH#31064
dti = date_range("2019-12-31 23:59:55.999999999", periods=10, freq="s")
- ser = pd.Series(range(10), index=dti)
+ ser = Series(range(10), index=dti)
result = ser[partial_dtime]
expected = ser.iloc[:5]
tm.assert_series_equal(result, expected)
@@ -321,7 +277,7 @@ def test_partial_slicing_with_multiindex(self):
tm.assert_frame_equal(result, expected)
expected = df_multi.loc[
- (pd.Timestamp("2013-06-19 09:30:00", tz=None), "ACCT1", "ABC")
+ (Timestamp("2013-06-19 09:30:00", tz=None), "ACCT1", "ABC")
]
result = df_multi.loc[("2013-06-19 09:30:00", "ACCT1", "ABC")]
tm.assert_series_equal(result, expected)
@@ -334,31 +290,31 @@ def test_partial_slicing_with_multiindex(self):
# GH 4294
# partial slice on a series mi
- s = pd.DataFrame(
- np.random.rand(1000, 1000), index=pd.date_range("2000-1-1", periods=1000)
+ s = DataFrame(
+ np.random.rand(1000, 1000), index=date_range("2000-1-1", periods=1000)
).stack()
s2 = s[:-1].copy()
expected = s2["2000-1-4"]
- result = s2[pd.Timestamp("2000-1-4")]
+ result = s2[Timestamp("2000-1-4")]
tm.assert_series_equal(result, expected)
- result = s[pd.Timestamp("2000-1-4")]
+ result = s[Timestamp("2000-1-4")]
expected = s["2000-1-4"]
tm.assert_series_equal(result, expected)
- df2 = pd.DataFrame(s)
+ df2 = DataFrame(s)
expected = df2.xs("2000-1-4")
- result = df2.loc[pd.Timestamp("2000-1-4")]
+ result = df2.loc[Timestamp("2000-1-4")]
tm.assert_frame_equal(result, expected)
def test_partial_slice_doesnt_require_monotonicity(self):
# For historical reasons.
- s = pd.Series(np.arange(10), pd.date_range("2014-01-01", periods=10))
+ s = Series(np.arange(10), date_range("2014-01-01", periods=10))
nonmonotonic = s[[3, 5, 4]]
expected = nonmonotonic.iloc[:0]
- timestamp = pd.Timestamp("2014-01-10")
+ timestamp = Timestamp("2014-01-10")
tm.assert_series_equal(nonmonotonic["2014-01-10":], expected)
with pytest.raises(KeyError, match=r"Timestamp\('2014-01-10 00:00:00'\)"):
@@ -370,9 +326,9 @@ def test_partial_slice_doesnt_require_monotonicity(self):
def test_loc_datetime_length_one(self):
# GH16071
- df = pd.DataFrame(
+ df = DataFrame(
columns=["1"],
- index=pd.date_range("2016-10-01T00:00:00", "2016-10-01T23:59:59"),
+ index=date_range("2016-10-01T00:00:00", "2016-10-01T23:59:59"),
)
result = df.loc[datetime(2016, 10, 1) :]
tm.assert_frame_equal(result, df)
@@ -403,10 +359,10 @@ def test_selection_by_datetimelike(self, datetimelike, op, expected):
df = DataFrame(
{
"A": [
- pd.Timestamp("20120101"),
- pd.Timestamp("20130101"),
+ Timestamp("20120101"),
+ Timestamp("20130101"),
np.nan,
- pd.Timestamp("20130103"),
+ Timestamp("20130103"),
]
}
)
@@ -418,26 +374,26 @@ def test_selection_by_datetimelike(self, datetimelike, op, expected):
"start",
[
"2018-12-02 21:50:00+00:00",
- pd.Timestamp("2018-12-02 21:50:00+00:00"),
- pd.Timestamp("2018-12-02 21:50:00+00:00").to_pydatetime(),
+ Timestamp("2018-12-02 21:50:00+00:00"),
+ Timestamp("2018-12-02 21:50:00+00:00").to_pydatetime(),
],
)
@pytest.mark.parametrize(
"end",
[
"2018-12-02 21:52:00+00:00",
- pd.Timestamp("2018-12-02 21:52:00+00:00"),
- pd.Timestamp("2018-12-02 21:52:00+00:00").to_pydatetime(),
+ Timestamp("2018-12-02 21:52:00+00:00"),
+ Timestamp("2018-12-02 21:52:00+00:00").to_pydatetime(),
],
)
def test_getitem_with_datestring_with_UTC_offset(self, start, end):
# GH 24076
- idx = pd.date_range(
+ idx = date_range(
start="2018-12-02 14:50:00-07:00",
end="2018-12-02 14:50:00-07:00",
freq="1min",
)
- df = pd.DataFrame(1, index=idx, columns=["A"])
+ df = DataFrame(1, index=idx, columns=["A"])
result = df[start:end]
expected = df.iloc[0:3, :]
tm.assert_frame_equal(result, expected)
@@ -454,11 +410,9 @@ def test_getitem_with_datestring_with_UTC_offset(self, start, end):
def test_slice_reduce_to_series(self):
# GH 27516
- df = pd.DataFrame(
- {"A": range(24)}, index=pd.date_range("2000", periods=24, freq="M")
- )
- expected = pd.Series(
- range(12), index=pd.date_range("2000", periods=12, freq="M"), name="A"
+ df = DataFrame({"A": range(24)}, index=date_range("2000", periods=24, freq="M"))
+ expected = Series(
+ range(12), index=date_range("2000", periods=12, freq="M"), name="A"
)
result = df.loc["2000", "A"]
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexes/multi/test_partial_indexing.py b/pandas/tests/indexes/multi/test_partial_indexing.py
index b00018d2ceb69..7dfe0b20a7478 100644
--- a/pandas/tests/indexes/multi/test_partial_indexing.py
+++ b/pandas/tests/indexes/multi/test_partial_indexing.py
@@ -1,19 +1,11 @@
-import numpy as np
import pytest
-import pandas as pd
-from pandas import DataFrame, MultiIndex, date_range
+from pandas import DataFrame, IndexSlice, MultiIndex, date_range
import pandas._testing as tm
-def test_partial_string_timestamp_multiindex():
- # GH10331
- dr = pd.date_range("2016-01-01", "2016-01-03", freq="12H")
- abc = ["a", "b", "c"]
- ix = pd.MultiIndex.from_product([dr, abc])
- df = pd.DataFrame({"c1": range(0, 15)}, index=ix)
- idx = pd.IndexSlice
-
+@pytest.fixture
+def df():
# c1
# 2016-01-01 00:00:00 a 0
# b 1
@@ -30,33 +22,39 @@ def test_partial_string_timestamp_multiindex():
# 2016-01-03 00:00:00 a 12
# b 13
# c 14
+ dr = date_range("2016-01-01", "2016-01-03", freq="12H")
+ abc = ["a", "b", "c"]
+ mi = MultiIndex.from_product([dr, abc])
+ frame = DataFrame({"c1": range(0, 15)}, index=mi)
+ return frame
+
+def test_partial_string_matching_single_index(df):
# partial string matching on a single index
- for df_swap in (df.swaplevel(), df.swaplevel(0), df.swaplevel(0, 1)):
+ for df_swap in [df.swaplevel(), df.swaplevel(0), df.swaplevel(0, 1)]:
df_swap = df_swap.sort_index()
just_a = df_swap.loc["a"]
result = just_a.loc["2016-01-01"]
- expected = df.loc[idx[:, "a"], :].iloc[0:2]
+ expected = df.loc[IndexSlice[:, "a"], :].iloc[0:2]
expected.index = expected.index.droplevel(1)
tm.assert_frame_equal(result, expected)
+
+def test_partial_string_timestamp_multiindex(df):
+ # GH10331
+ df_swap = df.swaplevel(0, 1).sort_index()
+ SLC = IndexSlice
+
# indexing with IndexSlice
- result = df.loc[idx["2016-01-01":"2016-02-01", :], :]
+ result = df.loc[SLC["2016-01-01":"2016-02-01", :], :]
expected = df
tm.assert_frame_equal(result, expected)
# match on secondary index
- result = df_swap.loc[idx[:, "2016-01-01":"2016-01-01"], :]
+ result = df_swap.loc[SLC[:, "2016-01-01":"2016-01-01"], :]
expected = df_swap.iloc[[0, 1, 5, 6, 10, 11]]
tm.assert_frame_equal(result, expected)
- # Even though this syntax works on a single index, this is somewhat
- # ambiguous and we don't want to extend this behavior forward to work
- # in multi-indexes. This would amount to selecting a scalar from a
- # column.
- with pytest.raises(KeyError, match="'2016-01-01'"):
- df["2016-01-01"]
-
# partial string match on year only
result = df.loc["2016"]
expected = df
@@ -73,7 +71,7 @@ def test_partial_string_timestamp_multiindex():
tm.assert_frame_equal(result, expected)
# partial string match on secondary index
- result = df_swap.loc[idx[:, "2016-01-02"], :]
+ result = df_swap.loc[SLC[:, "2016-01-02"], :]
expected = df_swap.iloc[[2, 3, 7, 8, 12, 13]]
tm.assert_frame_equal(result, expected)
@@ -86,11 +84,18 @@ def test_partial_string_timestamp_multiindex():
with pytest.raises(KeyError, match="'2016-01-01'"):
df_swap.loc["2016-01-01"]
- # GH12685 (partial string with daily resolution or below)
- dr = date_range("2013-01-01", periods=100, freq="D")
- ix = MultiIndex.from_product([dr, ["a", "b"]])
- df = DataFrame(np.random.randn(200, 1), columns=["A"], index=ix)
- result = df.loc[idx["2013-03":"2013-03", :], :]
+def test_partial_string_timestamp_multiindex_str_key_raises(df):
+ # Even though this syntax works on a single index, this is somewhat
+ # ambiguous and we don't want to extend this behavior forward to work
+ # in multi-indexes. This would amount to selecting a scalar from a
+ # column.
+ with pytest.raises(KeyError, match="'2016-01-01'"):
+ df["2016-01-01"]
+
+
+def test_partial_string_timestamp_multiindex_daily_resolution(df):
+ # GH12685 (partial string with daily resolution or below)
+ result = df.loc[IndexSlice["2013-03":"2013-03", :], :]
expected = df.iloc[118:180]
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py
index ad9ee7bd2594d..aa99207261e4e 100644
--- a/pandas/tests/indexes/period/test_partial_slicing.py
+++ b/pandas/tests/indexes/period/test_partial_slicing.py
@@ -1,45 +1,11 @@
import numpy as np
import pytest
-import pandas as pd
-from pandas import DataFrame, Period, Series, period_range
+from pandas import DataFrame, Series, date_range, period_range
import pandas._testing as tm
class TestPeriodIndex:
- def test_slice_with_negative_step(self):
- ts = Series(np.arange(20), period_range("2014-01", periods=20, freq="M"))
- SLC = pd.IndexSlice
-
- def assert_slices_equivalent(l_slc, i_slc):
- tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc])
- tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
- tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
-
- assert_slices_equivalent(SLC[Period("2014-10") :: -1], SLC[9::-1])
- assert_slices_equivalent(SLC["2014-10"::-1], SLC[9::-1])
-
- assert_slices_equivalent(SLC[: Period("2014-10") : -1], SLC[:8:-1])
- assert_slices_equivalent(SLC[:"2014-10":-1], SLC[:8:-1])
-
- assert_slices_equivalent(SLC["2015-02":"2014-10":-1], SLC[13:8:-1])
- assert_slices_equivalent(
- SLC[Period("2015-02") : Period("2014-10") : -1], SLC[13:8:-1]
- )
- assert_slices_equivalent(SLC["2015-02" : Period("2014-10") : -1], SLC[13:8:-1])
- assert_slices_equivalent(SLC[Period("2015-02") : "2014-10" : -1], SLC[13:8:-1])
-
- assert_slices_equivalent(SLC["2014-10":"2015-02":-1], SLC[:0])
-
- def test_slice_with_zero_step_raises(self):
- ts = Series(np.arange(20), period_range("2014-01", periods=20, freq="M"))
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
-
def test_pindex_slice_index(self):
pi = period_range(start="1/1/10", end="12/31/12", freq="M")
s = Series(np.random.rand(len(pi)), index=pi)
@@ -50,91 +16,86 @@ def test_pindex_slice_index(self):
exp = s[12:24]
tm.assert_series_equal(res, exp)
- def test_range_slice_day(self):
+ @pytest.mark.parametrize("make_range", [date_range, period_range])
+ def test_range_slice_day(self, make_range):
# GH#6716
- didx = pd.date_range(start="2013/01/01", freq="D", periods=400)
- pidx = period_range(start="2013/01/01", freq="D", periods=400)
+ idx = make_range(start="2013/01/01", freq="D", periods=400)
msg = "slice indices must be integers or None or have an __index__ method"
- for idx in [didx, pidx]:
- # slices against index should raise IndexError
- values = [
- "2014",
- "2013/02",
- "2013/01/02",
- "2013/02/01 9H",
- "2013/02/01 09:00",
- ]
- for v in values:
- with pytest.raises(TypeError, match=msg):
- idx[v:]
-
- s = Series(np.random.rand(len(idx)), index=idx)
-
- tm.assert_series_equal(s["2013/01/02":], s[1:])
- tm.assert_series_equal(s["2013/01/02":"2013/01/05"], s[1:5])
- tm.assert_series_equal(s["2013/02":], s[31:])
- tm.assert_series_equal(s["2014":], s[365:])
-
- invalid = ["2013/02/01 9H", "2013/02/01 09:00"]
- for v in invalid:
- with pytest.raises(TypeError, match=msg):
- idx[v:]
-
- def test_range_slice_seconds(self):
+ # slices against index should raise IndexError
+ values = [
+ "2014",
+ "2013/02",
+ "2013/01/02",
+ "2013/02/01 9H",
+ "2013/02/01 09:00",
+ ]
+ for v in values:
+ with pytest.raises(TypeError, match=msg):
+ idx[v:]
+
+ s = Series(np.random.rand(len(idx)), index=idx)
+
+ tm.assert_series_equal(s["2013/01/02":], s[1:])
+ tm.assert_series_equal(s["2013/01/02":"2013/01/05"], s[1:5])
+ tm.assert_series_equal(s["2013/02":], s[31:])
+ tm.assert_series_equal(s["2014":], s[365:])
+
+ invalid = ["2013/02/01 9H", "2013/02/01 09:00"]
+ for v in invalid:
+ with pytest.raises(TypeError, match=msg):
+ idx[v:]
+
+ @pytest.mark.parametrize("make_range", [date_range, period_range])
+ def test_range_slice_seconds(self, make_range):
# GH#6716
- didx = pd.date_range(start="2013/01/01 09:00:00", freq="S", periods=4000)
- pidx = period_range(start="2013/01/01 09:00:00", freq="S", periods=4000)
+ idx = make_range(start="2013/01/01 09:00:00", freq="S", periods=4000)
msg = "slice indices must be integers or None or have an __index__ method"
- for idx in [didx, pidx]:
- # slices against index should raise IndexError
- values = [
- "2014",
- "2013/02",
- "2013/01/02",
- "2013/02/01 9H",
- "2013/02/01 09:00",
- ]
- for v in values:
- with pytest.raises(TypeError, match=msg):
- idx[v:]
-
- s = Series(np.random.rand(len(idx)), index=idx)
-
- tm.assert_series_equal(s["2013/01/01 09:05":"2013/01/01 09:10"], s[300:660])
- tm.assert_series_equal(
- s["2013/01/01 10:00":"2013/01/01 10:05"], s[3600:3960]
- )
- tm.assert_series_equal(s["2013/01/01 10H":], s[3600:])
- tm.assert_series_equal(s[:"2013/01/01 09:30"], s[:1860])
- for d in ["2013/01/01", "2013/01", "2013"]:
- tm.assert_series_equal(s[d:], s)
-
- def test_range_slice_outofbounds(self):
+ # slices against index should raise IndexError
+ values = [
+ "2014",
+ "2013/02",
+ "2013/01/02",
+ "2013/02/01 9H",
+ "2013/02/01 09:00",
+ ]
+ for v in values:
+ with pytest.raises(TypeError, match=msg):
+ idx[v:]
+
+ s = Series(np.random.rand(len(idx)), index=idx)
+
+ tm.assert_series_equal(s["2013/01/01 09:05":"2013/01/01 09:10"], s[300:660])
+ tm.assert_series_equal(s["2013/01/01 10:00":"2013/01/01 10:05"], s[3600:3960])
+ tm.assert_series_equal(s["2013/01/01 10H":], s[3600:])
+ tm.assert_series_equal(s[:"2013/01/01 09:30"], s[:1860])
+ for d in ["2013/01/01", "2013/01", "2013"]:
+ tm.assert_series_equal(s[d:], s)
+
+ @pytest.mark.parametrize("make_range", [date_range, period_range])
+ def test_range_slice_outofbounds(self, make_range):
# GH#5407
- didx = pd.date_range(start="2013/10/01", freq="D", periods=10)
- pidx = period_range(start="2013/10/01", freq="D", periods=10)
-
- for idx in [didx, pidx]:
- df = DataFrame(dict(units=[100 + i for i in range(10)]), index=idx)
- empty = DataFrame(index=type(idx)([], freq="D"), columns=["units"])
- empty["units"] = empty["units"].astype("int64")
-
- tm.assert_frame_equal(df["2013/09/01":"2013/09/30"], empty)
- tm.assert_frame_equal(df["2013/09/30":"2013/10/02"], df.iloc[:2])
- tm.assert_frame_equal(df["2013/10/01":"2013/10/02"], df.iloc[:2])
- tm.assert_frame_equal(df["2013/10/02":"2013/09/30"], empty)
- tm.assert_frame_equal(df["2013/10/15":"2013/10/17"], empty)
- tm.assert_frame_equal(df["2013-06":"2013-09"], empty)
- tm.assert_frame_equal(df["2013-11":"2013-12"], empty)
+ idx = make_range(start="2013/10/01", freq="D", periods=10)
+
+ df = DataFrame(dict(units=[100 + i for i in range(10)]), index=idx)
+ empty = DataFrame(index=type(idx)([], freq="D"), columns=["units"])
+ empty["units"] = empty["units"].astype("int64")
+
+ tm.assert_frame_equal(df["2013/09/01":"2013/09/30"], empty)
+ tm.assert_frame_equal(df["2013/09/30":"2013/10/02"], df.iloc[:2])
+ tm.assert_frame_equal(df["2013/10/01":"2013/10/02"], df.iloc[:2])
+ tm.assert_frame_equal(df["2013/10/02":"2013/09/30"], empty)
+ tm.assert_frame_equal(df["2013/10/15":"2013/10/17"], empty)
+ tm.assert_frame_equal(df["2013-06":"2013-09"], empty)
+ tm.assert_frame_equal(df["2013-11":"2013-12"], empty)
def test_partial_slice_doesnt_require_monotonicity(self):
# See also: DatetimeIndex test ofm the same name
- dti = pd.date_range("2014-01-01", periods=30, freq="30D")
+ dti = date_range("2014-01-01", periods=30, freq="30D")
pi = dti.to_period("D")
- ser_montonic = pd.Series(np.arange(30), index=pi)
+ ser_montonic = Series(np.arange(30), index=pi)
shuffler = list(range(0, 30, 2)) + list(range(1, 31, 2))
ser = ser_montonic[shuffler]
diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
index 10ad521ce4f76..e5f509acf4734 100644
--- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py
+++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
@@ -1,8 +1,7 @@
import numpy as np
import pytest
-import pandas as pd
-from pandas import Series, Timedelta, timedelta_range
+from pandas import Series, timedelta_range
import pandas._testing as tm
@@ -46,42 +45,3 @@ def test_partial_slice_high_reso(self):
result = s["1 days, 10:11:12.001001"]
assert result == s.iloc[1001]
-
- def test_slice_with_negative_step(self):
- ts = Series(np.arange(20), timedelta_range("0", periods=20, freq="H"))
- SLC = pd.IndexSlice
-
- def assert_slices_equivalent(l_slc, i_slc):
- expected = ts.iloc[i_slc]
-
- tm.assert_series_equal(ts[l_slc], expected)
- tm.assert_series_equal(ts.loc[l_slc], expected)
- tm.assert_series_equal(ts.loc[l_slc], expected)
-
- assert_slices_equivalent(SLC[Timedelta(hours=7) :: -1], SLC[7::-1])
- assert_slices_equivalent(SLC["7 hours"::-1], SLC[7::-1])
-
- assert_slices_equivalent(SLC[: Timedelta(hours=7) : -1], SLC[:6:-1])
- assert_slices_equivalent(SLC[:"7 hours":-1], SLC[:6:-1])
-
- assert_slices_equivalent(SLC["15 hours":"7 hours":-1], SLC[15:6:-1])
- assert_slices_equivalent(
- SLC[Timedelta(hours=15) : Timedelta(hours=7) : -1], SLC[15:6:-1]
- )
- assert_slices_equivalent(
- SLC["15 hours" : Timedelta(hours=7) : -1], SLC[15:6:-1]
- )
- assert_slices_equivalent(
- SLC[Timedelta(hours=15) : "7 hours" : -1], SLC[15:6:-1]
- )
-
- assert_slices_equivalent(SLC["7 hours":"15 hours":-1], SLC[0:0:-1])
-
- def test_slice_with_zero_step_raises(self):
- ts = Series(np.arange(20), timedelta_range("0", periods=20, freq="H"))
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
- with pytest.raises(ValueError, match="slice step cannot be zero"):
- ts.loc[::0]
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 16b6604c7fc52..8fa28d7b854c8 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -8,7 +8,18 @@
from pandas.core.dtypes.common import is_scalar
import pandas as pd
-from pandas import Categorical, DataFrame, MultiIndex, Series, Timedelta, Timestamp
+from pandas import (
+ Categorical,
+ DataFrame,
+ IndexSlice,
+ MultiIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+ period_range,
+ timedelta_range,
+)
import pandas._testing as tm
from pandas.tseries.offsets import BDay
@@ -877,3 +888,54 @@ def test_getitem_unrecognized_scalar():
result = ser[key]
assert result == 2
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ date_range("2014-01-01", periods=20, freq="MS"),
+ period_range("2014-01", periods=20, freq="M"),
+ timedelta_range("0", periods=20, freq="H"),
+ ],
+)
+def test_slice_with_zero_step_raises(index):
+ ts = Series(np.arange(20), index)
+
+ with pytest.raises(ValueError, match="slice step cannot be zero"):
+ ts[::0]
+ with pytest.raises(ValueError, match="slice step cannot be zero"):
+ ts.loc[::0]
+ with pytest.raises(ValueError, match="slice step cannot be zero"):
+ ts.iloc[::0]
+
+
+@pytest.mark.parametrize(
+ "index",
+ [
+ date_range("2014-01-01", periods=20, freq="MS"),
+ period_range("2014-01", periods=20, freq="M"),
+ timedelta_range("0", periods=20, freq="H"),
+ ],
+)
+def test_slice_with_negative_step(index):
+ def assert_slices_equivalent(l_slc, i_slc):
+ expected = ts.iloc[i_slc]
+
+ tm.assert_series_equal(ts[l_slc], expected)
+ tm.assert_series_equal(ts.loc[l_slc], expected)
+ tm.assert_series_equal(ts.loc[l_slc], expected)
+
+ keystr1 = str(index[9])
+ keystr2 = str(index[13])
+ box = type(index[0])
+
+ ts = Series(np.arange(20), index)
+ SLC = IndexSlice
+
+ for key in [keystr1, box(keystr1)]:
+ assert_slices_equivalent(SLC[key::-1], SLC[9::-1])
+ assert_slices_equivalent(SLC[:key:-1], SLC[:8:-1])
+
+ for key2 in [keystr2, box(keystr2)]:
+ assert_slices_equivalent(SLC[key2:key:-1], SLC[13:8:-1])
+ assert_slices_equivalent(SLC[key:key2:-1], SLC[0:0:-1])
| https://api.github.com/repos/pandas-dev/pandas/pulls/33873 | 2020-04-29T17:29:00Z | 2020-04-29T22:35:48Z | 2020-04-29T22:35:48Z | 2020-04-29T22:37:38Z | |
DOC: Remove TODO from `test_openpyxl` | diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
index 60c943d95e510..5f8d58ea1f105 100644
--- a/pandas/tests/io/excel/test_openpyxl.py
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -109,7 +109,6 @@ def test_write_append_mode(ext, mode, expected):
def test_to_excel_with_openpyxl_engine(ext, tmpdir):
# GH 29854
- # TODO: Fix this once newer version of openpyxl fixes the bug
df1 = DataFrame({"A": np.linspace(1, 10, 10)})
df2 = DataFrame({"B": np.linspace(1, 20, 10)})
df = pd.concat([df1, df2], axis=1)
| xref #29862
Brought up by @jbrockmendel seems the `xfail` has been removed and version has been unpinned, just a tiny PR to remove this `TODO` from tests. probably people who fixed it forgot to remove this.
cc @jbrockmendel
| https://api.github.com/repos/pandas-dev/pandas/pulls/33872 | 2020-04-29T16:52:53Z | 2020-04-29T19:26:12Z | 2020-04-29T19:26:12Z | 2020-04-30T09:00:59Z |
DOC/CLN: Fix to_numpy docstrings | diff --git a/pandas/core/base.py b/pandas/core/base.py
index ee514888c6331..7ea2ff95ea0de 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -753,7 +753,7 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs):
dtype : str or numpy.dtype, optional
The dtype to pass to :meth:`numpy.asarray`.
copy : bool, default False
- Whether to ensure that the returned value is a not a view on
+ Whether to ensure that the returned value is not a view on
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4b4801f4e8c58..f8cb99e2b2e75 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1301,7 +1301,7 @@ def to_numpy(self, dtype=None, copy: bool = False) -> np.ndarray:
dtype : str or numpy.dtype, optional
The dtype to pass to :meth:`numpy.asarray`.
copy : bool, default False
- Whether to ensure that the returned value is a not a view on
+ Whether to ensure that the returned value is not a view on
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33871 | 2020-04-29T16:40:33Z | 2020-04-29T21:49:00Z | 2020-04-29T21:49:00Z | 2020-04-29T23:13:47Z | |
TST/REF: collect Index tests by method | diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index e0e5beaf48e20..50983dbd8db22 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -5,46 +5,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Index, NaT, Timestamp, date_range, offsets
+from pandas import DataFrame, DatetimeIndex, Index, Timestamp, date_range, offsets
import pandas._testing as tm
randn = np.random.randn
class TestDatetimeIndex:
- def test_roundtrip_pickle_with_tz(self):
-
- # GH 8367
- # round-trip of timezone
- index = date_range("20130101", periods=3, tz="US/Eastern", name="foo")
- unpickled = tm.round_trip_pickle(index)
- tm.assert_index_equal(index, unpickled)
-
- def test_pickle(self):
-
- # GH#4606
- p = tm.round_trip_pickle(NaT)
- assert p is NaT
-
- idx = pd.to_datetime(["2013-01-01", NaT, "2014-01-06"])
- idx_p = tm.round_trip_pickle(idx)
- assert idx_p[0] == idx[0]
- assert idx_p[1] is NaT
- assert idx_p[2] == idx[2]
-
- # GH#11002
- # don't infer freq
- idx = date_range("1750-1-1", "2050-1-1", freq="7D")
- 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")
@@ -164,23 +131,6 @@ def test_append_nondatetimeindex(self):
result = rng.append(idx)
assert isinstance(result[0], Timestamp)
- def test_map(self):
- rng = date_range("1/1/2000", periods=10)
-
- f = lambda x: x.strftime("%Y%m%d")
- result = rng.map(f)
- exp = Index([f(x) for x in rng], dtype="<U8")
- tm.assert_index_equal(result, exp)
-
- def test_map_fallthrough(self, capsys):
- # GH#22067, check we don't get warnings about silently ignored errors
- dti = date_range("2017-01-01", "2018-01-01", freq="B")
-
- dti.map(lambda x: pd.Period(year=x.year, month=x.month, freq="M"))
-
- captured = capsys.readouterr()
- assert captured.err == ""
-
def test_iteration_preserves_tz(self):
# see gh-8890
index = date_range("2012-01-01", periods=3, freq="H", tz="US/Eastern")
@@ -264,14 +214,6 @@ def test_sort_values(self):
assert ordered[::-1].is_monotonic
tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1], dtype=np.intp))
- def test_map_bug_1677(self):
- index = DatetimeIndex(["2012-04-25 09:30:00.393000"])
- f = index.asof
-
- result = index.map(f)
- expected = Index([f(index[0])])
- tm.assert_index_equal(result, expected)
-
def test_groupby_function_tuple_1677(self):
df = DataFrame(np.random.rand(100), index=date_range("1/1/2000", periods=100))
monthly_group = df.groupby(lambda x: (x.year, x.month))
@@ -454,18 +396,6 @@ def test_to_frame_datetime_tz(self):
expected = DataFrame(idx, index=idx)
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize("name", [None, "name"])
- def test_index_map(self, name):
- # see GH20990
- count = 6
- index = pd.date_range("2018-01-01", periods=count, freq="M", name=name).map(
- lambda x: (x.year, x.month)
- )
- exp_index = pd.MultiIndex.from_product(
- ((2018,), range(1, 7)), names=[name, name]
- )
- tm.assert_index_equal(index, exp_index)
-
def test_split_non_utc(self):
# GH 14042
indices = pd.date_range("2016-01-01 00:00:00+0200", freq="S", periods=10)
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py
index d813604400f9a..d74b2bd03c0a0 100644
--- a/pandas/tests/indexes/datetimes/test_indexing.py
+++ b/pandas/tests/indexes/datetimes/test_indexing.py
@@ -518,6 +518,21 @@ def test_dti_contains_with_duplicates(self):
ix = DatetimeIndex([d, d])
assert d in ix
+ @pytest.mark.parametrize(
+ "vals",
+ [
+ [0, 1, 0],
+ [0, 0, -1],
+ [0, -1, -1],
+ ["2015", "2015", "2016"],
+ ["2015", "2015", "2014"],
+ ],
+ )
+ def test_contains_nonunique(self, vals):
+ # GH#9512
+ idx = DatetimeIndex(vals)
+ assert idx[0] in idx
+
class TestGetIndexer:
def test_get_indexer(self):
diff --git a/pandas/tests/indexes/datetimes/test_map.py b/pandas/tests/indexes/datetimes/test_map.py
new file mode 100644
index 0000000000000..2644ad7616b51
--- /dev/null
+++ b/pandas/tests/indexes/datetimes/test_map.py
@@ -0,0 +1,41 @@
+import pytest
+
+from pandas import DatetimeIndex, Index, MultiIndex, Period, date_range
+import pandas._testing as tm
+
+
+class TestMap:
+ def test_map(self):
+ rng = date_range("1/1/2000", periods=10)
+
+ f = lambda x: x.strftime("%Y%m%d")
+ result = rng.map(f)
+ exp = Index([f(x) for x in rng], dtype="<U8")
+ tm.assert_index_equal(result, exp)
+
+ def test_map_fallthrough(self, capsys):
+ # GH#22067, check we don't get warnings about silently ignored errors
+ dti = date_range("2017-01-01", "2018-01-01", freq="B")
+
+ dti.map(lambda x: Period(year=x.year, month=x.month, freq="M"))
+
+ captured = capsys.readouterr()
+ assert captured.err == ""
+
+ def test_map_bug_1677(self):
+ index = DatetimeIndex(["2012-04-25 09:30:00.393000"])
+ f = index.asof
+
+ result = index.map(f)
+ expected = Index([f(index[0])])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("name", [None, "name"])
+ def test_index_map(self, name):
+ # see GH#20990
+ count = 6
+ index = date_range("2018-01-01", periods=count, freq="M", name=name).map(
+ lambda x: (x.year, x.month)
+ )
+ exp_index = MultiIndex.from_product(((2018,), range(1, 7)), names=[name, name])
+ tm.assert_index_equal(index, exp_index)
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index 603a0a452391c..ea6381547009c 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -170,20 +170,6 @@ def test_value_counts_unique(self, tz_naive_fixture):
tm.assert_index_equal(idx.unique(), exp_idx)
- def test_nonunique_contains(self):
- # GH 9512
- for idx in map(
- DatetimeIndex,
- (
- [0, 1, 0],
- [0, 0, -1],
- [0, -1, -1],
- ["2015", "2015", "2016"],
- ["2015", "2015", "2014"],
- ),
- ):
- assert idx[0] in idx
-
@pytest.mark.parametrize(
"idx",
[
@@ -432,10 +418,6 @@ def test_comparison(self):
assert comp[11]
assert not comp[9]
- def test_pickle_unpickle(self):
- unpickled = tm.round_trip_pickle(self.rng)
- assert unpickled.freq is not None
-
def test_copy(self):
cp = self.rng.copy()
repr(cp)
@@ -478,9 +460,5 @@ def test_copy(self):
repr(cp)
tm.assert_index_equal(cp, self.rng)
- def test_pickle_unpickle(self):
- unpickled = tm.round_trip_pickle(self.rng)
- assert unpickled.freq is not None
-
def test_equals(self):
assert not self.rng.equals(list(self.rng))
diff --git a/pandas/tests/indexes/datetimes/test_pickle.py b/pandas/tests/indexes/datetimes/test_pickle.py
new file mode 100644
index 0000000000000..bb08d4c66cb3c
--- /dev/null
+++ b/pandas/tests/indexes/datetimes/test_pickle.py
@@ -0,0 +1,41 @@
+import pytest
+
+from pandas import NaT, date_range, to_datetime
+import pandas._testing as tm
+
+
+class TestPickle:
+ def test_pickle(self):
+ # GH#4606
+ idx = to_datetime(["2013-01-01", NaT, "2014-01-06"])
+ idx_p = tm.round_trip_pickle(idx)
+ assert idx_p[0] == idx[0]
+ assert idx_p[1] is NaT
+ assert idx_p[2] == idx[2]
+
+ def test_pickle_dont_infer_freq(self):
+ # GH##11002
+ # don't infer freq
+ idx = date_range("1750-1-1", "2050-1-1", freq="7D")
+ 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_roundtrip_pickle_with_tz(self):
+ # GH#8367
+ # round-trip of timezone
+ index = date_range("20130101", periods=3, tz="US/Eastern", name="foo")
+ unpickled = tm.round_trip_pickle(index)
+ tm.assert_index_equal(index, unpickled)
+
+ @pytest.mark.parametrize("freq", ["B", "C"])
+ def test_pickle_unpickle(self, freq):
+ rng = date_range("2009-01-01", "2010-01-01", freq=freq)
+ unpickled = tm.round_trip_pickle(rng)
+ assert unpickled.freq == freq
diff --git a/pandas/tests/indexes/period/test_factorize.py b/pandas/tests/indexes/period/test_factorize.py
new file mode 100644
index 0000000000000..7c9367a1011a2
--- /dev/null
+++ b/pandas/tests/indexes/period/test_factorize.py
@@ -0,0 +1,37 @@
+import numpy as np
+
+from pandas import PeriodIndex
+import pandas._testing as tm
+
+
+class TestFactorize:
+ def test_factorize(self):
+ idx1 = PeriodIndex(
+ ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"], freq="M"
+ )
+
+ exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
+ exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
+
+ arr, idx = idx1.factorize()
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, exp_idx)
+
+ arr, idx = idx1.factorize(sort=True)
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, exp_idx)
+
+ idx2 = PeriodIndex(
+ ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"], freq="M"
+ )
+
+ exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)
+ arr, idx = idx2.factorize(sort=True)
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, exp_idx)
+
+ exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
+ exp_idx = PeriodIndex(["2014-03", "2014-02", "2014-01"], freq="M")
+ arr, idx = idx2.factorize()
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, exp_idx)
diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py
index f0efff4bbdd88..2779cd92fca00 100644
--- a/pandas/tests/indexes/period/test_indexing.py
+++ b/pandas/tests/indexes/period/test_indexing.py
@@ -764,6 +764,27 @@ def test_contains(self):
assert p3 not in idx0
+ def test_contains_freq_mismatch(self):
+ rng = period_range("2007-01", freq="M", periods=10)
+
+ assert Period("2007-01", freq="M") in rng
+ assert not Period("2007-01", freq="D") in rng
+ assert not Period("2007-01", freq="2M") in rng
+
+ def test_contains_nat(self):
+ # see gh-13582
+ idx = period_range("2007-01", freq="M", periods=10)
+ assert NaT not in idx
+ assert None not in idx
+ assert float("nan") not in idx
+ assert np.nan not in idx
+
+ idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")
+ assert NaT in idx
+ assert None in idx
+ assert float("nan") in idx
+ assert np.nan in idx
+
class TestAsOfLocs:
def test_asof_locs_mismatched_type(self):
diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py
index 0ce10fb8779a1..d247d6571f5d0 100644
--- a/pandas/tests/indexes/period/test_period.py
+++ b/pandas/tests/indexes/period/test_period.py
@@ -318,37 +318,6 @@ def test_period_reindex_with_object(
expected = pd.Series(expected_values, index=object_index)
tm.assert_series_equal(result, expected)
- def test_factorize(self):
- idx1 = PeriodIndex(
- ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"], freq="M"
- )
-
- exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
- exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
-
- arr, idx = idx1.factorize()
- tm.assert_numpy_array_equal(arr, exp_arr)
- tm.assert_index_equal(idx, exp_idx)
-
- arr, idx = idx1.factorize(sort=True)
- tm.assert_numpy_array_equal(arr, exp_arr)
- tm.assert_index_equal(idx, exp_idx)
-
- idx2 = PeriodIndex(
- ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"], freq="M"
- )
-
- exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)
- arr, idx = idx2.factorize(sort=True)
- tm.assert_numpy_array_equal(arr, exp_arr)
- tm.assert_index_equal(idx, exp_idx)
-
- exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
- exp_idx = PeriodIndex(["2014-03", "2014-02", "2014-01"], freq="M")
- arr, idx = idx2.factorize()
- tm.assert_numpy_array_equal(arr, exp_arr)
- tm.assert_index_equal(idx, exp_idx)
-
def test_is_(self):
create_index = lambda: period_range(freq="A", start="1/1/2001", end="12/1/2009")
index = create_index()
@@ -367,27 +336,6 @@ def test_is_(self):
assert not index.is_(index - 2)
assert not index.is_(index - 0)
- def test_contains(self):
- rng = period_range("2007-01", freq="M", periods=10)
-
- assert Period("2007-01", freq="M") in rng
- assert not Period("2007-01", freq="D") in rng
- assert not Period("2007-01", freq="2M") in rng
-
- def test_contains_nat(self):
- # see gh-13582
- idx = period_range("2007-01", freq="M", periods=10)
- assert NaT not in idx
- assert None not in idx
- assert float("nan") not in idx
- assert np.nan not in idx
-
- idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")
- assert NaT in idx
- assert None in idx
- assert float("nan") in idx
- assert np.nan in idx
-
def test_periods_number_check(self):
msg = (
"Of the three parameters: start, end, and periods, exactly two "
diff --git a/pandas/tests/indexes/timedeltas/test_searchsorted.py b/pandas/tests/indexes/timedeltas/test_searchsorted.py
new file mode 100644
index 0000000000000..4806a9acff96f
--- /dev/null
+++ b/pandas/tests/indexes/timedeltas/test_searchsorted.py
@@ -0,0 +1,26 @@
+import numpy as np
+import pytest
+
+from pandas import Series, TimedeltaIndex, Timestamp, array
+import pandas._testing as tm
+
+
+class TestSearchSorted:
+ @pytest.mark.parametrize("klass", [list, np.array, array, Series])
+ def test_searchsorted_different_argument_classes(self, klass):
+ idx = TimedeltaIndex(["1 day", "2 days", "3 days"])
+ result = idx.searchsorted(klass(idx))
+ expected = np.arange(len(idx), dtype=result.dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = idx._data.searchsorted(klass(idx))
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2],
+ )
+ def test_searchsorted_invalid_argument_dtype(self, arg):
+ idx = TimedeltaIndex(["1 day", "2 days", "3 days"])
+ msg = "searchsorted requires compatible dtype"
+ with pytest.raises(TypeError, match=msg):
+ idx.searchsorted(arg)
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index 5efa1a75700e0..a0521658ffc1e 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -11,7 +11,6 @@
Series,
Timedelta,
TimedeltaIndex,
- array,
date_range,
timedelta_range,
)
@@ -108,26 +107,6 @@ def test_sort_values(self):
tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1]), check_dtype=False)
- @pytest.mark.parametrize("klass", [list, np.array, array, Series])
- def test_searchsorted_different_argument_classes(self, klass):
- idx = TimedeltaIndex(["1 day", "2 days", "3 days"])
- result = idx.searchsorted(klass(idx))
- expected = np.arange(len(idx), dtype=result.dtype)
- tm.assert_numpy_array_equal(result, expected)
-
- result = idx._data.searchsorted(klass(idx))
- tm.assert_numpy_array_equal(result, expected)
-
- @pytest.mark.parametrize(
- "arg",
- [[1, 2], ["a", "b"], [pd.Timestamp("2020-01-01", tz="Europe/London")] * 2],
- )
- def test_searchsorted_invalid_argument_dtype(self, arg):
- idx = TimedeltaIndex(["1 day", "2 days", "3 days"])
- msg = "searchsorted requires compatible dtype"
- with pytest.raises(TypeError, match=msg):
- idx.searchsorted(arg)
-
def test_argmin_argmax(self):
idx = TimedeltaIndex(["1 day 00:00:05", "1 day 00:00:01", "1 day 00:00:02"])
assert idx.argmin() == 1
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 5b73118cfdc0c..5cc2399b6ed72 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -102,14 +102,15 @@ def test_setitem_series_object(self, val, exp_dtype):
"val,exp_dtype",
[(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, np.object)],
)
- def test_setitem_series_int64(self, val, exp_dtype):
+ def test_setitem_series_int64(self, val, exp_dtype, request):
obj = pd.Series([1, 2, 3, 4])
assert obj.dtype == np.int64
if exp_dtype is np.float64:
exp = pd.Series([1, 1, 3, 4])
self._assert_setitem_series_conversion(obj, 1.1, exp, np.int64)
- pytest.xfail("GH12747 The result must be float")
+ mark = pytest.mark.xfail(reason="GH12747 The result must be float")
+ request.node.add_marker(mark)
exp = pd.Series([1, val, 3, 4])
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@@ -117,14 +118,17 @@ def test_setitem_series_int64(self, val, exp_dtype):
@pytest.mark.parametrize(
"val,exp_dtype", [(np.int32(1), np.int8), (np.int16(2 ** 9), np.int16)]
)
- def test_setitem_series_int8(self, val, exp_dtype):
+ def test_setitem_series_int8(self, val, exp_dtype, request):
obj = pd.Series([1, 2, 3, 4], dtype=np.int8)
assert obj.dtype == np.int8
if exp_dtype is np.int16:
exp = pd.Series([1, 0, 3, 4], dtype=np.int8)
self._assert_setitem_series_conversion(obj, val, exp, np.int8)
- pytest.xfail("BUG: it must be Series([1, 1, 3, 4], dtype=np.int16")
+ mark = pytest.mark.xfail(
+ reason="BUG: it must be Series([1, 1, 3, 4], dtype=np.int16"
+ )
+ request.node.add_marker(mark)
exp = pd.Series([1, val, 3, 4], dtype=np.int8)
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@@ -171,22 +175,25 @@ def test_setitem_series_complex128(self, val, exp_dtype):
(True, np.bool),
],
)
- def test_setitem_series_bool(self, val, exp_dtype):
+ def test_setitem_series_bool(self, val, exp_dtype, request):
obj = pd.Series([True, False, True, False])
assert obj.dtype == np.bool
+ mark = None
if exp_dtype is np.int64:
exp = pd.Series([True, True, True, False])
self._assert_setitem_series_conversion(obj, val, exp, np.bool)
- pytest.xfail("TODO_GH12747 The result must be int")
+ mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be int")
elif exp_dtype is np.float64:
exp = pd.Series([True, True, True, False])
self._assert_setitem_series_conversion(obj, val, exp, np.bool)
- pytest.xfail("TODO_GH12747 The result must be float")
+ mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be float")
elif exp_dtype is np.complex128:
exp = pd.Series([True, True, True, False])
self._assert_setitem_series_conversion(obj, val, exp, np.bool)
- pytest.xfail("TODO_GH12747 The result must be complex")
+ mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be complex")
+ if mark is not None:
+ request.node.add_marker(mark)
exp = pd.Series([True, val, True, False])
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@@ -318,7 +325,7 @@ def test_setitem_index_int64(self, val, exp_dtype):
@pytest.mark.parametrize(
"val,exp_dtype", [(5, IndexError), (5.1, np.float64), ("x", np.object)]
)
- def test_setitem_index_float64(self, val, exp_dtype):
+ def test_setitem_index_float64(self, val, exp_dtype, request):
obj = pd.Series([1, 2, 3, 4], index=[1.1, 2.1, 3.1, 4.1])
assert obj.index.dtype == np.float64
@@ -327,31 +334,31 @@ def test_setitem_index_float64(self, val, exp_dtype):
temp = obj.copy()
with pytest.raises(exp_dtype):
temp[5] = 5
- pytest.xfail("TODO_GH12747 The result must be float")
-
+ mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be float")
+ request.node.add_marker(mark)
exp_index = pd.Index([1.1, 2.1, 3.1, 4.1, val])
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
def test_setitem_series_period(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_complex128(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_bool(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_datetime64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_datetime64tz(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_timedelta64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_setitem_index_period(self):
- pass
+ pytest.xfail("Test not implemented")
class TestInsertIndexCoercion(CoercionBase):
@@ -503,10 +510,10 @@ def test_insert_index_period(self, insert, coerced_val, coerced_dtype):
pd.Index(data, freq="M")
def test_insert_index_complex128(self):
- pass
+ pytest.xfail("Test not implemented")
def test_insert_index_bool(self):
- pass
+ pytest.xfail("Test not implemented")
class TestWhereCoercion(CoercionBase):
@@ -757,16 +764,16 @@ def test_where_index_datetime64tz(self):
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
def test_where_index_complex128(self):
- pass
+ pytest.xfail("Test not implemented")
def test_where_index_bool(self):
- pass
+ pytest.xfail("Test not implemented")
def test_where_series_timedelta64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_where_series_period(self):
- pass
+ pytest.xfail("Test not implemented")
@pytest.mark.parametrize(
"value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")]
@@ -818,7 +825,7 @@ class TestFillnaSeriesCoercion(CoercionBase):
method = "fillna"
def test_has_comprehensive_tests(self):
- pass
+ pytest.xfail("Test not implemented")
def _assert_fillna_conversion(self, original, value, expected, expected_dtype):
""" test coercion triggered by fillna """
@@ -943,28 +950,28 @@ def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype):
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
def test_fillna_series_int64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_index_int64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_series_bool(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_index_bool(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_series_timedelta64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_series_period(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_index_timedelta64(self):
- pass
+ pytest.xfail("Test not implemented")
def test_fillna_index_period(self):
- pass
+ pytest.xfail("Test not implemented")
class TestReplaceSeriesCoercion(CoercionBase):
@@ -1121,4 +1128,4 @@ def test_replace_series_datetime_datetime(self, how, to_key, from_key):
tm.assert_series_equal(result, exp)
def test_replace_series_period(self):
- pass
+ pytest.xfail("Test not implemented")
diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index 0e5414a8b4d2d..edda0391f87c9 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -546,3 +546,9 @@ def test_nat_addsub_tdlike_scalar(obj):
assert NaT + obj is NaT
assert obj + NaT is NaT
assert NaT - obj is NaT
+
+
+def test_pickle():
+ # GH#4606
+ p = tm.round_trip_pickle(NaT)
+ assert p is NaT
| xfail tests in test_coercion rather than silently passing | https://api.github.com/repos/pandas-dev/pandas/pulls/33870 | 2020-04-29T15:03:43Z | 2020-04-29T22:37:11Z | 2020-04-29T22:37:11Z | 2020-04-29T22:38:22Z |
DOC: Remove deprecated Y and M from to_timedelta | diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py
index 48f30acf269da..51b404b46f321 100644
--- a/pandas/core/tools/timedeltas.py
+++ b/pandas/core/tools/timedeltas.py
@@ -28,8 +28,8 @@ def to_timedelta(arg, unit="ns", errors="raise"):
The data to be converted to timedelta.
unit : str, default 'ns'
Denotes the unit of the arg. Possible values:
- ('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',
- 'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
+ ('W', 'D', 'days', 'day', 'hours', hour', 'hr', 'h',
+ 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
'sec', 'second', 'ms', 'milliseconds', 'millisecond',
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
[`to_timedelta()`](https://github.com/pandas-dev/pandas/blob/master/pandas/core/tools/timedeltas.py#L84-L88) blocks those arguments anyway, so no reason to include them in the docstring. | https://api.github.com/repos/pandas-dev/pandas/pulls/33869 | 2020-04-29T14:29:15Z | 2020-04-29T22:48:13Z | 2020-04-29T22:48:13Z | 2020-04-29T22:48:17Z |
DOC: Code Standards Broken Link | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index ba7f7eb907f4a..1073959de4456 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -581,7 +581,7 @@ do not make sudden changes to the code that could have the potential to break
a lot of user code as a result, that is, we need it to be as *backwards compatible*
as possible to avoid mass breakages.
-Additional standards are outlined on the `pandas code style guide <code_style>`_
+Additional standards are outlined on the :ref:`pandas code style guide <code_style>`
Optional dependencies
---------------------
| - [ ] closes #33852
- [ ] 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/33865 | 2020-04-29T11:18:29Z | 2020-04-29T12:13:07Z | 2020-04-29T12:13:07Z | 2020-04-29T12:16:22Z |
TYP/CLN: remove #type: ignore from pandas\tests\base\test_conversion.py | diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index 59f9103072fe9..1f4bc024e14d4 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -391,10 +391,11 @@ def test_to_numpy_dtype(as_series):
),
],
)
-@pytest.mark.parametrize("container", [pd.Series, pd.Index]) # type: ignore
-def test_to_numpy_na_value_numpy_dtype(container, values, dtype, na_value, expected):
- s = container(values)
- result = s.to_numpy(dtype=dtype, na_value=na_value)
+def test_to_numpy_na_value_numpy_dtype(
+ index_or_series, values, dtype, na_value, expected
+):
+ obj = index_or_series(values)
+ result = obj.to_numpy(dtype=dtype, na_value=na_value)
expected = np.array(expected)
tm.assert_numpy_array_equal(result, expected)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33864 | 2020-04-29T10:56:21Z | 2020-04-29T15:29:35Z | 2020-04-29T15:29:35Z | 2020-04-29T17:15:06Z | |
CLN: Assorted | diff --git a/.circleci/config.yml b/.circleci/config.yml
index 549a6374246a0..999bba1f9f77f 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -26,7 +26,6 @@ jobs:
image: ubuntu-2004:2022.04.1
resource_class: arm.large
environment:
- ENV_FILE: ci/deps/circle-38-arm64.yaml
TRIGGER_SOURCE: << pipeline.trigger_source >>
steps:
- checkout
diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst
index 184060d3cf697..311120fc527d4 100644
--- a/doc/source/development/contributing_codebase.rst
+++ b/doc/source/development/contributing_codebase.rst
@@ -770,7 +770,7 @@ install pandas) by typing::
your installation is probably fine and you can start contributing!
Often it is worth running only a subset of tests first around your changes before running the
-entire suite (tip: you can use the [pandas-coverage app](https://pandas-coverage.herokuapp.com/)
+entire suite (tip: you can use the [pandas-coverage app](https://pandas-coverage.herokuapp.com/))
to find out which tests hit the lines of code you've modified, and then run only those).
The easiest way to do this is with::
diff --git a/doc/source/getting_started/index.rst b/doc/source/getting_started/index.rst
index abb3aad8dbd3e..d9cb1de14aded 100644
--- a/doc/source/getting_started/index.rst
+++ b/doc/source/getting_started/index.rst
@@ -24,7 +24,7 @@ Installation
.. code-block:: bash
- conda install pandas
+ conda install -c conda-forge pandas
.. grid-item-card:: Prefer pip?
:class-card: install-card
diff --git a/web/pandas/community/ecosystem.md b/web/pandas/community/ecosystem.md
index 60b043cf052ce..957a8d38b204c 100644
--- a/web/pandas/community/ecosystem.md
+++ b/web/pandas/community/ecosystem.md
@@ -58,7 +58,7 @@ target values with cutoff times that can be used for supervised learning.
STUMPY is a powerful and scalable Python library for modern time series analysis.
At its core, STUMPY efficiently computes something called a
-`matrix profile <https://stumpy.readthedocs.io/en/latest/Tutorial_The_Matrix_Profile.html>`__,
+[matrix profile](https://stumpy.readthedocs.io/en/latest/Tutorial_The_Matrix_Profile.html),
which can be used for a wide variety of time series data mining tasks.
## Visualization
@@ -177,7 +177,7 @@ D-Tale integrates seamlessly with Jupyter notebooks, Python terminals, Kaggle
### [hvplot](https://hvplot.holoviz.org/index.html)
-hvPlot is a high-level plotting API for the PyData ecosystem built on `HoloViews <https://holoviews.org/>`__.
+hvPlot is a high-level plotting API for the PyData ecosystem built on [HoloViews](https://holoviews.org/).
It can be loaded as a native pandas plotting backend via
```python
@@ -207,8 +207,7 @@ are utilized by Jupyter Notebook for displaying (abbreviated) HTML or
LaTeX tables. LaTeX output is properly escaped. (Note: HTML tables may
or may not be compatible with non-HTML Jupyter output formats.)
-See `Options and Settings <options>` and
-`Available Options <options.available>`
+See [Options and Settings](https://pandas.pydata.org/docs/user_guide/options.html)
for pandas `display.` settings.
### [quantopian/qgrid](https://github.com/quantopian/qgrid)
@@ -355,7 +354,7 @@ Rigorously tested, it is a complete replacement for ``df.to_sql``.
### [Deltalake](https://pypi.org/project/deltalake)
Deltalake python package lets you access tables stored in
-`Delta Lake <https://delta.io/>`__ natively in Python without the need to use Spark or
+[Delta Lake](https://delta.io/) natively in Python without the need to use Spark or
JVM. It provides the ``delta_table.to_pyarrow_table().to_pandas()`` method to convert
any Delta table into Pandas dataframe.
@@ -510,8 +509,8 @@ assumptions about your datasets and check that they're *actually* true.
## Extension data types
Pandas provides an interface for defining
-`extension types <extending.extension-types>` to extend NumPy's type system. The following libraries
-implement that interface to provide types not found in NumPy or pandas,
+[extension types](https://pandas.pydata.org/docs/development/extending.html#extension-types) to extend NumPy's type system.
+The following librariesimplement that interface to provide types not found in NumPy or pandas,
which work well with pandas' data containers.
### [cyberpandas](https://cyberpandas.readthedocs.io/en/latest)
@@ -540,7 +539,8 @@ Text Extensions for Pandas provides extension types to cover common data structu
## Accessors
A directory of projects providing
-`extension accessors <extending.register-accessors>`. This is for users to discover new accessors and for library
+[extension accessors](https://pandas.pydata.org/docs/development/extending.html#registering-custom-accessors).
+This is for users to discover new accessors and for library
authors to coordinate on the namespace.
| Library | Accessor | Classes |
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53356 | 2023-05-23T17:56:00Z | 2023-05-30T20:11:51Z | 2023-05-30T20:11:51Z | 2023-05-30T20:11:54Z |
CLN: Apply.agg_list_like | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 020aa4e8916da..481217a7fb4af 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -324,6 +324,9 @@ def agg_list_like(self) -> DataFrame | Series:
keys = []
is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy))
+ is_ser_or_df = isinstance(obj, (ABCDataFrame, ABCSeries))
+ this_args = [self.axis, *self.args] if is_ser_or_df else self.args
+
context_manager: ContextManager
if is_groupby:
# When as_index=False, we combine all results using indices
@@ -336,12 +339,7 @@ def agg_list_like(self) -> DataFrame | Series:
if selected_obj.ndim == 1:
for a in arg:
colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
- if isinstance(colg, (ABCSeries, ABCDataFrame)):
- new_res = colg.aggregate(
- a, self.axis, *self.args, **self.kwargs
- )
- else:
- new_res = colg.aggregate(a, *self.args, **self.kwargs)
+ new_res = colg.aggregate(a, *this_args, **self.kwargs)
results.append(new_res)
# make sure we find a good name
@@ -352,12 +350,7 @@ def agg_list_like(self) -> DataFrame | Series:
indices = []
for index, col in enumerate(selected_obj):
colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
- if isinstance(colg, (ABCSeries, ABCDataFrame)):
- new_res = colg.aggregate(
- arg, self.axis, *self.args, **self.kwargs
- )
- else:
- new_res = colg.aggregate(arg, *self.args, **self.kwargs)
+ new_res = colg.aggregate(arg, *this_args, **self.kwargs)
results.append(new_res)
indices.append(index)
keys = selected_obj.columns.take(indices)
| small clean-up. | https://api.github.com/repos/pandas-dev/pandas/pulls/53353 | 2023-05-23T15:24:51Z | 2023-05-24T15:48:15Z | 2023-05-24T15:48:15Z | 2023-05-24T15:53:29Z |
DOC: Fixing EX01 - Added examples | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 64c5b735fdc8d..962e7cc86a98b 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -254,13 +254,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.util.hash_pandas_object \
pandas_object \
pandas.api.interchange.from_dataframe \
- pandas.Index.drop \
- pandas.Index.identical \
- pandas.Index.insert \
- pandas.Index.is_ \
- pandas.Index.take \
- pandas.Index.putmask \
- pandas.Index.unique \
pandas.Index.fillna \
pandas.Index.dropna \
pandas.Index.astype \
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 174c6625fb779..aa8bfb667f5be 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -799,6 +799,15 @@ def is_(self, other) -> bool:
See Also
--------
Index.identical : Works like ``Index.is_`` but also checks metadata.
+
+ Examples
+ --------
+ >>> idx1 = pd.Index(['1', '2', '3'])
+ >>> idx1.is_(idx1.view())
+ True
+
+ >>> idx1.is_(idx1.copy())
+ False
"""
if self is other:
return True
@@ -1089,6 +1098,12 @@ def astype(self, dtype, copy: bool = True):
--------
numpy.ndarray.take: Return an array formed from the
elements of a at the given indices.
+
+ Examples
+ --------
+ >>> idx = pd.Index(['a', 'b', 'c'])
+ >>> idx.take([2, 2, 1, 2])
+ Index(['c', 'c', 'b', 'c'], dtype='object')
"""
@Appender(_index_shared_docs["take"] % _index_doc_kwargs)
@@ -2966,6 +2981,12 @@ def unique(self, level: Hashable | None = None) -> Self:
--------
unique : Numpy array of unique values in that column.
Series.unique : Return unique values of Series object.
+
+ Examples
+ --------
+ >>> idx = pd.Index([1, 1, 2, 3, 3])
+ >>> idx.unique()
+ Index([1, 2, 3], dtype='int64')
"""
if level is not None:
self._validate_index_level(level)
@@ -5345,6 +5366,13 @@ def putmask(self, mask, value) -> Index:
--------
numpy.ndarray.putmask : Changes elements of an array
based on conditional and input values.
+
+ Examples
+ --------
+ >>> idx1 = pd.Index([1, 2, 3])
+ >>> idx2 = pd.Index([5, 6, 7])
+ >>> idx1.putmask([True, False, False], idx2)
+ Index([5, 2, 3], dtype='int64')
"""
mask, noop = validate_putmask(self._values, mask)
if noop:
@@ -5474,6 +5502,18 @@ def identical(self, other) -> bool:
bool
If two Index objects have equal elements and same type True,
otherwise False.
+
+ Examples
+ --------
+ >>> idx1 = pd.Index(['1', '2', '3'])
+ >>> idx2 = pd.Index(['1', '2', '3'])
+ >>> idx2.identical(idx1)
+ True
+
+ >>> idx1 = pd.Index(['1', '2', '3'], name="A")
+ >>> idx2 = pd.Index(['1', '2', '3'], name="B")
+ >>> idx2.identical(idx1)
+ False
"""
return (
self.equals(other)
@@ -6694,6 +6734,12 @@ def insert(self, loc: int, item) -> Index:
Returns
-------
Index
+
+ Examples
+ --------
+ >>> idx = pd.Index(['a', 'b', 'c'])
+ >>> idx.insert(1, 'x')
+ Index(['a', 'x', 'b', 'c'], dtype='object')
"""
item = lib.item_from_zerodim(item)
if is_valid_na_for_dtype(item, self.dtype) and self.dtype != object:
@@ -6755,6 +6801,12 @@ def drop(
------
KeyError
If not all of the labels are found in the selected axis
+
+ Examples
+ --------
+ >>> idx = pd.Index(['a', 'b', 'c'])
+ >>> idx.drop(['a'])
+ Index(['b', 'c'], dtype='object')
"""
if not isinstance(labels, Index):
# avoid materializing e.g. RangeIndex
| - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
Towards https://github.com/pandas-dev/pandas/issues/37875
| https://api.github.com/repos/pandas-dev/pandas/pulls/53352 | 2023-05-23T15:14:55Z | 2023-05-24T15:49:26Z | 2023-05-24T15:49:26Z | 2023-05-24T16:50:01Z |
DOC: Mention gurobipy-pandas in ecosystem | diff --git a/web/pandas/community/ecosystem.md b/web/pandas/community/ecosystem.md
index ebd1fc198dfcf..60b043cf052ce 100644
--- a/web/pandas/community/ecosystem.md
+++ b/web/pandas/community/ecosystem.md
@@ -321,7 +321,14 @@ which support geometric operations. If your work entails maps and
geographical coordinates, and you love pandas, you should take a close
look at Geopandas.
-### [staricase](https://github.com/staircase-dev/staircase)
+### [gurobipy-pandas](https://github.com/Gurobi/gurobipy-pandas)
+
+gurobipy-pandas provides a convenient accessor API to connect pandas with
+gurobipy. It enables users to more easily and efficiently build mathematical
+optimization models from data stored in DataFrames and Series, and to read
+solutions back directly as pandas objects.
+
+### [staircase](https://github.com/staircase-dev/staircase)
staircase is a data analysis package, built upon pandas and numpy, for modelling and
manipulation of mathematical step functions. It provides a rich variety of arithmetic
@@ -546,6 +553,7 @@ authors to coordinate on the namespace.
| [composeml](https://github.com/alteryx/compose) | `slice` | `DataFrame` |
| [datatest](https://datatest.readthedocs.io/en/stable/) | `validate` | `Series`, `DataFrame` |
| [composeml](https://github.com/alteryx/compose) | `slice` | `DataFrame` |
+ | [gurobipy-pandas](https://github.com/Gurobi/gurobipy-pandas) | `gppd` | `Series`, `DataFrame` |
| [staircase](https://www.staircase.dev/) | `sc` | `Series`, `DataFrame` |
| [woodwork](https://github.com/alteryx/woodwork) | `slice` | `Series`, `DataFrame` |
| Simple addition to the ecosystem page.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53349 | 2023-05-23T10:22:38Z | 2023-05-23T13:08:45Z | 2023-05-23T13:08:45Z | 2023-05-23T14:36:22Z |
CLN: refactor hash_array to resolve circular dependency | diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index 88dbee0808533..5fd962da0ec48 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -254,7 +254,7 @@ def hash_array(
encoding=encoding, hash_key=hash_key, categorize=categorize
)
- elif not isinstance(vals, np.ndarray):
+ if not isinstance(vals, np.ndarray):
# GH#42003
raise TypeError(
"hash_array requires np.ndarray or ExtensionArray, not "
@@ -275,14 +275,15 @@ def _hash_ndarray(
"""
dtype = vals.dtype
- # we'll be working with everything as 64-bit values, so handle this
- # 128-bit value early
+ # _hash_ndarray only takes 64-bit values, so handle 128-bit by parts
if np.issubdtype(dtype, np.complex128):
- return hash_array(np.real(vals)) + 23 * hash_array(np.imag(vals))
+ hash_real = _hash_ndarray(vals.real, encoding, hash_key, categorize)
+ hash_imag = _hash_ndarray(vals.imag, encoding, hash_key, categorize)
+ return hash_real + 23 * hash_imag
# First, turn whatever array this is into unsigned 64-bit ints, if we can
# manage it.
- elif dtype == bool:
+ if dtype == bool:
vals = vals.astype("u8")
elif issubclass(dtype.type, (np.datetime64, np.timedelta64)):
vals = vals.view("i8").astype("u8", copy=False)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53347 | 2023-05-23T02:29:32Z | 2023-05-24T17:49:57Z | 2023-05-24T17:49:56Z | 2023-05-25T00:17:30Z |
Refactor Extension Modules | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e3ebdb859319a..de4c6687fbc0f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -65,11 +65,7 @@ repos:
rev: 1.6.1
hooks:
- id: cpplint
- # We don't lint all C files because we don't want to lint any that are built
- # from Cython files nor do we want to lint C files that we didn't modify for
- # this particular codebase (e.g. src/headers, src/klib). However,
- # we can lint all header files since they aren't "generated" like C files are.
- exclude: ^pandas/_libs/src/(klib|headers)/
+ exclude: ^pandas/_libs/include/pandas/vendored/klib
args: [
--quiet,
'--extensions=c,h',
diff --git a/MANIFEST.in b/MANIFEST.in
index 361cd8ff9ec22..781a72fdb5481 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -57,6 +57,4 @@ prune pandas/tests/io/parser/data
# Selectively re-add *.cxx files that were excluded above
graft pandas/_libs/src
-graft pandas/_libs/tslibs/src
-include pandas/_libs/pd_parser.h
-include pandas/_libs/pd_parser.c
+graft pandas/_libs/include
diff --git a/pandas/_libs/tslibs/src/datetime/date_conversions.h b/pandas/_libs/include/pandas/datetime/date_conversions.h
similarity index 100%
rename from pandas/_libs/tslibs/src/datetime/date_conversions.h
rename to pandas/_libs/include/pandas/datetime/date_conversions.h
diff --git a/pandas/_libs/tslibs/src/datetime/pd_datetime.h b/pandas/_libs/include/pandas/datetime/pd_datetime.h
similarity index 97%
rename from pandas/_libs/tslibs/src/datetime/pd_datetime.h
rename to pandas/_libs/include/pandas/datetime/pd_datetime.h
index 4e3baf4b47ed0..55aa046cf076b 100644
--- a/pandas/_libs/tslibs/src/datetime/pd_datetime.h
+++ b/pandas/_libs/include/pandas/datetime/pd_datetime.h
@@ -22,9 +22,9 @@ See NUMPY_LICENSE.txt for the license.
#endif // NPY_NO_DEPRECATED_API
#include <numpy/ndarraytypes.h>
-#include "np_datetime.h"
-#include "np_datetime_strings.h"
-#include "date_conversions.h"
+#include "pandas/vendored/numpy/datetime/np_datetime.h"
+#include "pandas/vendored/numpy/datetime/np_datetime_strings.h"
+#include "pandas/datetime/date_conversions.h"
#ifdef __cplusplus
extern "C" {
diff --git a/pandas/_libs/src/inline_helper.h b/pandas/_libs/include/pandas/inline_helper.h
similarity index 100%
rename from pandas/_libs/src/inline_helper.h
rename to pandas/_libs/include/pandas/inline_helper.h
diff --git a/pandas/_libs/src/parser/io.h b/pandas/_libs/include/pandas/parser/io.h
similarity index 100%
rename from pandas/_libs/src/parser/io.h
rename to pandas/_libs/include/pandas/parser/io.h
diff --git a/pandas/_libs/pd_parser.h b/pandas/_libs/include/pandas/parser/pd_parser.h
similarity index 99%
rename from pandas/_libs/pd_parser.h
rename to pandas/_libs/include/pandas/parser/pd_parser.h
index 72254090c0056..1ea94fde593ef 100644
--- a/pandas/_libs/pd_parser.h
+++ b/pandas/_libs/include/pandas/parser/pd_parser.h
@@ -14,7 +14,7 @@ extern "C" {
#define PY_SSIZE_T_CLEAN
#include <Python.h>
-#include "src/parser/tokenizer.h"
+#include "pandas/parser/tokenizer.h"
typedef struct {
int (*to_double)(char *, double *, char, char, int *);
diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/include/pandas/parser/tokenizer.h
similarity index 98%
rename from pandas/_libs/src/parser/tokenizer.h
rename to pandas/_libs/include/pandas/parser/tokenizer.h
index 7e8c3d102ac63..a53d09012116d 100644
--- a/pandas/_libs/src/parser/tokenizer.h
+++ b/pandas/_libs/include/pandas/parser/tokenizer.h
@@ -19,10 +19,10 @@ See LICENSE for the license
#define ERROR_INVALID_CHARS 3
#include <stdint.h>
-#include "../inline_helper.h"
-#include "../headers/portable.h"
+#include "pandas/inline_helper.h"
+#include "pandas/portable.h"
-#include "khash.h"
+#include "pandas/vendored/klib/khash.h"
#define STREAM_INIT_SIZE 32
diff --git a/pandas/_libs/src/headers/portable.h b/pandas/_libs/include/pandas/portable.h
similarity index 67%
rename from pandas/_libs/src/headers/portable.h
rename to pandas/_libs/include/pandas/portable.h
index a34f833b7fd6b..954b5c3cce082 100644
--- a/pandas/_libs/src/headers/portable.h
+++ b/pandas/_libs/include/pandas/portable.h
@@ -1,9 +1,18 @@
+/*
+Copyright (c) 2016, PyData Development Team
+All rights reserved.
+
+Distributed under the terms of the BSD Simplified License.
+
+The full license is in the LICENSE file, distributed with this software.
+*/
+
#pragma once
#include <string.h>
#if defined(_MSC_VER)
-#define strcasecmp( s1, s2 ) _stricmp( s1, s2 )
+#define strcasecmp(s1, s2) _stricmp(s1, s2)
#endif
// GH-23516 - works around locale perf issues
diff --git a/pandas/_libs/src/skiplist.h b/pandas/_libs/include/pandas/skiplist.h
similarity index 99%
rename from pandas/_libs/src/skiplist.h
rename to pandas/_libs/include/pandas/skiplist.h
index d94099da5890e..3be9e51f42e09 100644
--- a/pandas/_libs/src/skiplist.h
+++ b/pandas/_libs/include/pandas/skiplist.h
@@ -19,7 +19,7 @@ Python recipe (https://rhettinger.wordpress.com/2010/02/06/lost-knowledge/)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "inline_helper.h"
+#include "pandas/inline_helper.h"
PANDAS_INLINE float __skiplist_nanf(void) {
const union {
diff --git a/pandas/_libs/src/klib/khash.h b/pandas/_libs/include/pandas/vendored/klib/khash.h
similarity index 99%
rename from pandas/_libs/src/klib/khash.h
rename to pandas/_libs/include/pandas/vendored/klib/khash.h
index e17d82d51f0fb..95b25d053a9df 100644
--- a/pandas/_libs/src/klib/khash.h
+++ b/pandas/_libs/include/pandas/vendored/klib/khash.h
@@ -112,7 +112,7 @@ int main() {
#include <stdlib.h>
#include <string.h>
#include <limits.h>
-#include "../inline_helper.h"
+#include "pandas/inline_helper.h"
// hooks for memory allocator, C-runtime allocator used per default
diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/include/pandas/vendored/klib/khash_python.h
similarity index 100%
rename from pandas/_libs/src/klib/khash_python.h
rename to pandas/_libs/include/pandas/vendored/klib/khash_python.h
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.h b/pandas/_libs/include/pandas/vendored/numpy/datetime/np_datetime.h
similarity index 100%
rename from pandas/_libs/tslibs/src/datetime/np_datetime.h
rename to pandas/_libs/include/pandas/vendored/numpy/datetime/np_datetime.h
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.h b/pandas/_libs/include/pandas/vendored/numpy/datetime/np_datetime_strings.h
similarity index 100%
rename from pandas/_libs/tslibs/src/datetime/np_datetime_strings.h
rename to pandas/_libs/include/pandas/vendored/numpy/datetime/np_datetime_strings.h
diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/include/pandas/vendored/ujson/lib/ultrajson.h
similarity index 99%
rename from pandas/_libs/src/ujson/lib/ultrajson.h
rename to pandas/_libs/include/pandas/vendored/ujson/lib/ultrajson.h
index d359cf27ff7e2..54bcca9e4136c 100644
--- a/pandas/_libs/src/ujson/lib/ultrajson.h
+++ b/pandas/_libs/include/pandas/vendored/ujson/lib/ultrajson.h
@@ -53,7 +53,7 @@ tree doesn't have cyclic references.
#include <stdio.h>
#include <wchar.h>
-#include "../../headers/portable.h"
+#include "pandas/portable.h"
// Don't output any extra whitespaces when encoding
#define JSON_NO_EXTRA_WHITESPACE
diff --git a/pandas/_libs/src/ujson/python/version.h b/pandas/_libs/include/pandas/vendored/ujson/python/version.h
similarity index 100%
rename from pandas/_libs/src/ujson/python/version.h
rename to pandas/_libs/include/pandas/vendored/ujson/python/version.h
diff --git a/pandas/_libs/khash.pxd b/pandas/_libs/khash.pxd
index a9f819e5e16db..c439e1cca772b 100644
--- a/pandas/_libs/khash.pxd
+++ b/pandas/_libs/khash.pxd
@@ -15,7 +15,7 @@ from numpy cimport (
)
-cdef extern from "khash_python.h":
+cdef extern from "pandas/vendored/klib/khash_python.h":
const int KHASH_TRACE_DOMAIN
ctypedef uint32_t khuint_t
diff --git a/pandas/_libs/khash_for_primitive_helper.pxi.in b/pandas/_libs/khash_for_primitive_helper.pxi.in
index d0934b3e0ee6e..d3391d4028938 100644
--- a/pandas/_libs/khash_for_primitive_helper.pxi.in
+++ b/pandas/_libs/khash_for_primitive_helper.pxi.in
@@ -24,7 +24,7 @@ primitive_types = [('int64', 'int64_t'),
{{for name, c_type in primitive_types}}
-cdef extern from "khash_python.h":
+cdef extern from "pandas/vendored/klib/khash_python.h":
ctypedef struct kh_{{name}}_t:
khuint_t n_buckets, size, n_occupied, upper_bound
uint32_t *flags
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 80592d4f67c98..59a9d0752805b 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -93,7 +93,7 @@ cdef extern from "numpy/arrayobject.h":
cdef extern from "numpy/ndarrayobject.h":
bint PyArray_CheckScalar(obj) nogil
-cdef extern from "pd_parser.h":
+cdef extern from "pandas/parser/pd_parser.h":
int floatify(object, float64_t *result, int *maybe_int) except -1
void PandasParser_IMPORT()
diff --git a/pandas/_libs/meson.build b/pandas/_libs/meson.build
index 382247c63c1ad..5e59f15d0d089 100644
--- a/pandas/_libs/meson.build
+++ b/pandas/_libs/meson.build
@@ -61,44 +61,33 @@ subdir('tslibs')
libs_sources = {
# Dict of extension name -> dict of {sources, include_dirs, and deps}
# numpy include dir is implicitly included
- 'algos': {'sources': ['algos.pyx', _algos_common_helper, _algos_take_helper, _khash_primitive_helper],
- 'include_dirs': klib_include},
+ 'algos': {'sources': ['algos.pyx', _algos_common_helper, _algos_take_helper, _khash_primitive_helper]},
'arrays': {'sources': ['arrays.pyx']},
'groupby': {'sources': ['groupby.pyx']},
'hashing': {'sources': ['hashing.pyx']},
- 'hashtable': {'sources': ['hashtable.pyx', _khash_primitive_helper, _hashtable_class_helper, _hashtable_func_helper],
- 'include_dirs': klib_include},
- 'index': {'sources': ['index.pyx', _index_class_helper],
- 'include_dirs': [klib_include, 'tslibs']},
+ 'hashtable': {'sources': ['hashtable.pyx', _khash_primitive_helper, _hashtable_class_helper, _hashtable_func_helper]},
+ 'index': {'sources': ['index.pyx', _index_class_helper]},
'indexing': {'sources': ['indexing.pyx']},
'internals': {'sources': ['internals.pyx']},
- 'interval': {'sources': ['interval.pyx', _intervaltree_helper],
- 'include_dirs': [klib_include, 'tslibs']},
+ 'interval': {'sources': ['interval.pyx', _intervaltree_helper]},
'join': {'sources': ['join.pyx', _khash_primitive_helper],
- 'include_dirs': klib_include,
'deps': _khash_primitive_helper_dep},
- 'lib': {'sources': ['lib.pyx', 'src/parser/tokenizer.c'],
- 'include_dirs': [klib_include, inc_datetime]},
- 'missing': {'sources': ['missing.pyx'],
- 'include_dirs': [inc_datetime]},
- 'pandas_datetime': {'sources': ['tslibs/src/datetime/np_datetime.c',
- 'tslibs/src/datetime/np_datetime_strings.c',
- 'tslibs/src/datetime/date_conversions.c',
- 'tslibs/src/datetime/pd_datetime.c']},
- #'include_dirs':
+ 'lib': {'sources': ['lib.pyx', 'src/parser/tokenizer.c']},
+ 'missing': {'sources': ['missing.pyx']},
+ 'pandas_datetime': {'sources': ['src/vendored/numpy/datetime/np_datetime.c',
+ 'src/vendored/numpy/datetime/np_datetime_strings.c',
+ 'src/datetime/date_conversions.c',
+ 'src/datetime/pd_datetime.c']},
'pandas_parser': {'sources': ['src/parser/tokenizer.c',
'src/parser/io.c',
- 'pd_parser.c'],
- 'include_dirs': [klib_include]},
+ 'src/parser/pd_parser.c']},
'parsers': {'sources': ['parsers.pyx', 'src/parser/tokenizer.c', 'src/parser/io.c'],
- 'include_dirs': [klib_include, 'src'],
'deps': _khash_primitive_helper_dep},
- 'json': {'sources': ['src/ujson/python/ujson.c',
- 'src/ujson/python/objToJSON.c',
- 'src/ujson/python/JSONtoObj.c',
- 'src/ujson/lib/ultrajsonenc.c',
- 'src/ujson/lib/ultrajsondec.c'],
- 'include_dirs': ['tslibs/src/datetime', 'src/ujson/lib', 'src/ujson/python']},
+ 'json': {'sources': ['src/vendored/ujson/python/ujson.c',
+ 'src/vendored/ujson/python/objToJSON.c',
+ 'src/vendored/ujson/python/JSONtoObj.c',
+ 'src/vendored/ujson/lib/ultrajsonenc.c',
+ 'src/vendored/ujson/lib/ultrajsondec.c']},
'ops': {'sources': ['ops.pyx']},
'ops_dispatch': {'sources': ['ops_dispatch.pyx']},
'properties': {'sources': ['properties.pyx']},
@@ -106,8 +95,7 @@ libs_sources = {
'sas': {'sources': ['sas.pyx']},
'byteswap': {'sources': ['byteswap.pyx']},
'sparse': {'sources': ['sparse.pyx', _sparse_op_helper]},
- 'tslib': {'sources': ['tslib.pyx'],
- 'include_dirs': inc_datetime},
+ 'tslib': {'sources': ['tslib.pyx']},
'testing': {'sources': ['testing.pyx']},
'writers': {'sources': ['writers.pyx']}
}
@@ -118,7 +106,7 @@ foreach ext_name, ext_dict : libs_sources
ext_name,
ext_dict.get('sources'),
cython_args: ['--include-dir', meson.current_build_dir()],
- include_directories: [inc_np] + ext_dict.get('include_dirs', ''),
+ include_directories: [inc_np, inc_pd],
dependencies: ext_dict.get('deps', ''),
subdir: 'pandas/_libs',
install: true
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index a45299c8ba896..10b2427835ed1 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -117,7 +117,7 @@ cdef:
int64_t DEFAULT_CHUNKSIZE = 256 * 1024
-cdef extern from "headers/portable.h":
+cdef extern from "pandas/portable.h":
# I *think* this is here so that strcasecmp is defined on Windows
# so we don't get
# `parsers.obj : error LNK2001: unresolved external symbol strcasecmp`
@@ -127,7 +127,7 @@ cdef extern from "headers/portable.h":
pass
-cdef extern from "parser/tokenizer.h":
+cdef extern from "pandas/parser/tokenizer.h":
ctypedef enum ParserState:
START_RECORD
@@ -245,7 +245,7 @@ cdef extern from "parser/tokenizer.h":
void COLITER_NEXT(coliter_t, const char *) nogil
-cdef extern from "pd_parser.h":
+cdef extern from "pandas/parser/pd_parser.h":
void *new_rd_source(object obj) except NULL
int del_rd_source(void *src)
diff --git a/pandas/_libs/tslibs/src/datetime/date_conversions.c b/pandas/_libs/src/datetime/date_conversions.c
similarity index 94%
rename from pandas/_libs/tslibs/src/datetime/date_conversions.c
rename to pandas/_libs/src/datetime/date_conversions.c
index 190713d62d306..84fc5507010ed 100644
--- a/pandas/_libs/tslibs/src/datetime/date_conversions.c
+++ b/pandas/_libs/src/datetime/date_conversions.c
@@ -8,9 +8,9 @@ The full license is in the LICENSE file, distributed with this software.
// Conversion routines that are useful for serialization,
// but which don't interact with JSON objects directly
-#include "date_conversions.h"
-#include "np_datetime.h"
-#include "np_datetime_strings.h"
+#include "pandas/datetime/date_conversions.h"
+#include "pandas/vendored/numpy/datetime/np_datetime.h"
+#include "pandas/vendored/numpy/datetime/np_datetime_strings.h"
/*
* Function: scaleNanosecToUnit
diff --git a/pandas/_libs/tslibs/src/datetime/pd_datetime.c b/pandas/_libs/src/datetime/pd_datetime.c
similarity index 99%
rename from pandas/_libs/tslibs/src/datetime/pd_datetime.c
rename to pandas/_libs/src/datetime/pd_datetime.c
index 98b6073d7a488..fc2cbcab90174 100644
--- a/pandas/_libs/tslibs/src/datetime/pd_datetime.c
+++ b/pandas/_libs/src/datetime/pd_datetime.c
@@ -20,7 +20,7 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt
#include <Python.h>
#include "datetime.h"
-#include "pd_datetime.h"
+#include "pandas/datetime/pd_datetime.h"
static void pandas_datetime_destructor(PyObject *op) {
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c
index 38304cca94a12..e00c5c1e807a7 100644
--- a/pandas/_libs/src/parser/io.c
+++ b/pandas/_libs/src/parser/io.c
@@ -7,7 +7,7 @@ Distributed under the terms of the BSD Simplified License.
The full license is in the LICENSE file, distributed with this software.
*/
-#include "io.h"
+#include "pandas/parser/io.h"
/*
On-disk FILE, uncompressed
diff --git a/pandas/_libs/pd_parser.c b/pandas/_libs/src/parser/pd_parser.c
similarity index 98%
rename from pandas/_libs/pd_parser.c
rename to pandas/_libs/src/parser/pd_parser.c
index 15d82b59df3e8..c429f17c1cb8b 100644
--- a/pandas/_libs/pd_parser.c
+++ b/pandas/_libs/src/parser/pd_parser.c
@@ -8,8 +8,8 @@ Distributed under the terms of the BSD Simplified License.
*/
#define _PANDAS_PARSER_IMPL
-#include "pd_parser.h"
-#include "src/parser/io.h"
+#include "pandas/parser/pd_parser.h"
+#include "pandas/parser/io.h"
static int to_double(char *item, double *p_value, char sci, char decimal,
int *maybe_int) {
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index e60fc6bf75f91..abd3fb9e1fef3 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -17,13 +17,13 @@ GitHub. See Python Software Foundation License and BSD licenses for these.
*/
-#include "tokenizer.h"
+#include "pandas/parser/tokenizer.h"
#include <ctype.h>
#include <float.h>
#include <math.h>
-#include "../headers/portable.h"
+#include "pandas/portable.h"
void coliter_setup(coliter_t *self, parser_t *parser, int64_t i,
int64_t start) {
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c
similarity index 99%
rename from pandas/_libs/tslibs/src/datetime/np_datetime.c
rename to pandas/_libs/src/vendored/numpy/datetime/np_datetime.c
index e4d9c5dcd63ea..7e5cb53cf8f62 100644
--- a/pandas/_libs/tslibs/src/datetime/np_datetime.c
+++ b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c
@@ -25,7 +25,7 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
#include <numpy/ndarraytypes.h>
-#include "np_datetime.h"
+#include "pandas/vendored/numpy/datetime/np_datetime.h"
const int days_per_month_table[2][12] = {
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c b/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c
similarity index 99%
rename from pandas/_libs/tslibs/src/datetime/np_datetime_strings.c
rename to pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c
index f1f03e6467eac..629d88ca6f589 100644
--- a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c
+++ b/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c
@@ -34,8 +34,8 @@ This file implements string parsing and creation for NumPy datetime.
#include <numpy/arrayscalars.h>
#include <numpy/ndarraytypes.h>
-#include "np_datetime.h"
-#include "np_datetime_strings.h"
+#include "pandas/vendored/numpy/datetime/np_datetime.h"
+#include "pandas/vendored/numpy/datetime/np_datetime_strings.h"
/*
diff --git a/pandas/_libs/src/ujson/lib/ultrajsondec.c b/pandas/_libs/src/vendored/ujson/lib/ultrajsondec.c
similarity index 99%
rename from pandas/_libs/src/ujson/lib/ultrajsondec.c
rename to pandas/_libs/src/vendored/ujson/lib/ultrajsondec.c
index 5347db1655669..9ec12cb242728 100644
--- a/pandas/_libs/src/ujson/lib/ultrajsondec.c
+++ b/pandas/_libs/src/vendored/ujson/lib/ultrajsondec.c
@@ -46,7 +46,7 @@ Numeric decoder derived from TCL library
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
-#include "ultrajson.h"
+#include "pandas/vendored/ujson/lib/ultrajson.h"
#ifndef TRUE
#define TRUE 1
diff --git a/pandas/_libs/src/ujson/lib/ultrajsonenc.c b/pandas/_libs/src/vendored/ujson/lib/ultrajsonenc.c
similarity index 99%
rename from pandas/_libs/src/ujson/lib/ultrajsonenc.c
rename to pandas/_libs/src/vendored/ujson/lib/ultrajsonenc.c
index 169c5b6889077..726676799af65 100644
--- a/pandas/_libs/src/ujson/lib/ultrajsonenc.c
+++ b/pandas/_libs/src/vendored/ujson/lib/ultrajsonenc.c
@@ -45,7 +45,7 @@ Numeric decoder derived from TCL library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "ultrajson.h"
+#include "pandas/vendored/ujson/lib/ultrajson.h"
#ifndef TRUE
#define TRUE 1
diff --git a/pandas/_libs/src/ujson/python/JSONtoObj.c b/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c
similarity index 99%
rename from pandas/_libs/src/ujson/python/JSONtoObj.c
rename to pandas/_libs/src/vendored/ujson/python/JSONtoObj.c
index d7086ffba623a..f4055fcedcfa6 100644
--- a/pandas/_libs/src/ujson/python/JSONtoObj.c
+++ b/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c
@@ -40,7 +40,7 @@ Numeric decoder derived from TCL library
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <numpy/arrayobject.h>
-#include <ultrajson.h>
+#include "pandas/vendored/ujson/lib/ultrajson.h"
#define PRINTMARK()
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/vendored/ujson/python/objToJSON.c
similarity index 99%
rename from pandas/_libs/src/ujson/python/objToJSON.c
rename to pandas/_libs/src/vendored/ujson/python/objToJSON.c
index 1b8ba8f3f7e6c..65b468f268d75 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/vendored/ujson/python/objToJSON.c
@@ -46,9 +46,9 @@ Numeric decoder derived from TCL library
#include <numpy/arrayscalars.h>
#include <numpy/ndarraytypes.h>
#include <numpy/npy_math.h>
-#include <ultrajson.h>
+#include "pandas/vendored/ujson/lib/ultrajson.h"
#include "datetime.h"
-#include "pd_datetime.h"
+#include "pandas/datetime/pd_datetime.h"
npy_int64 get_nat(void) { return NPY_MIN_INT64; }
diff --git a/pandas/_libs/src/ujson/python/ujson.c b/pandas/_libs/src/vendored/ujson/python/ujson.c
similarity index 99%
rename from pandas/_libs/src/ujson/python/ujson.c
rename to pandas/_libs/src/vendored/ujson/python/ujson.c
index 5c87ee6dd7ddc..15ea4b056b02d 100644
--- a/pandas/_libs/src/ujson/python/ujson.c
+++ b/pandas/_libs/src/vendored/ujson/python/ujson.c
@@ -35,7 +35,7 @@ Numeric decoder derived from TCL library
* Copyright (c) 1994 Sun Microsystems, Inc.
*/
-#include "version.h"
+#include "pandas/vendored/ujson/python/version.h"
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#define PY_ARRAY_UNIQUE_SYMBOL UJSON_NUMPY
diff --git a/pandas/_libs/tslibs/meson.build b/pandas/_libs/tslibs/meson.build
index fc8c9e609c416..4a51f8dc1e461 100644
--- a/pandas/_libs/tslibs/meson.build
+++ b/pandas/_libs/tslibs/meson.build
@@ -4,30 +4,19 @@ tslibs_sources = {
'base': {'sources': ['base.pyx']},
'ccalendar': {'sources': ['ccalendar.pyx']},
'dtypes': {'sources': ['dtypes.pyx']},
- 'conversion': {'sources': ['conversion.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'fields': {'sources': ['fields.pyx', 'src/datetime/np_datetime.c']},
+ 'conversion': {'sources': ['conversion.pyx']},
+ 'fields': {'sources': ['fields.pyx']},
'nattype': {'sources': ['nattype.pyx']},
- 'np_datetime': {'sources': ['np_datetime.pyx', 'src/datetime/np_datetime.c', 'src/datetime/np_datetime_strings.c'],
- 'include_dirs': inc_datetime},
- 'offsets': {'sources': ['offsets.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'parsing': {'sources': ['parsing.pyx', '../src/parser/tokenizer.c'],
- 'include_dirs': klib_include},
- 'period': {'sources': ['period.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'strptime': {'sources': ['strptime.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'timedeltas': {'sources': ['timedeltas.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'timestamps': {'sources': ['timestamps.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'timezones': {'sources': ['timezones.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'tzconversion': {'sources': ['tzconversion.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime},
- 'vectorized': {'sources': ['vectorized.pyx', 'src/datetime/np_datetime.c'],
- 'include_dirs': inc_datetime}
+ 'np_datetime': {'sources': ['np_datetime.pyx']},
+ 'offsets': {'sources': ['offsets.pyx']},
+ 'parsing': {'sources': ['parsing.pyx', '../src/parser/tokenizer.c']},
+ 'period': {'sources': ['period.pyx']},
+ 'strptime': {'sources': ['strptime.pyx']},
+ 'timedeltas': {'sources': ['timedeltas.pyx']},
+ 'timestamps': {'sources': ['timestamps.pyx']},
+ 'timezones': {'sources': ['timezones.pyx']},
+ 'tzconversion': {'sources': ['tzconversion.pyx']},
+ 'vectorized': {'sources': ['vectorized.pyx']},
}
foreach ext_name, ext_dict : tslibs_sources
@@ -35,7 +24,7 @@ foreach ext_name, ext_dict : tslibs_sources
ext_name,
ext_dict.get('sources'),
cython_args: ['--include-dir', meson.current_build_dir()],
- include_directories: [inc_np] + ext_dict.get('include_dirs', ''),
+ include_directories: [inc_np, inc_pd],
dependencies: ext_dict.get('deps', ''),
subdir: 'pandas/_libs/tslibs',
install: true
diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd
index 15230c47ae252..60532174e8bdc 100644
--- a/pandas/_libs/tslibs/np_datetime.pxd
+++ b/pandas/_libs/tslibs/np_datetime.pxd
@@ -55,7 +55,7 @@ cdef extern from "numpy/ndarraytypes.h":
int64_t NPY_DATETIME_NAT # elswhere we call this NPY_NAT
-cdef extern from "src/datetime/pd_datetime.h":
+cdef extern from "pandas/datetime/pd_datetime.h":
ctypedef struct pandas_timedeltastruct:
int64_t days
int32_t hrs, min, sec, ms, us, ns, seconds, microseconds, nanoseconds
diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx
index 2eebde982789c..990f862c3d105 100644
--- a/pandas/_libs/tslibs/np_datetime.pyx
+++ b/pandas/_libs/tslibs/np_datetime.pyx
@@ -36,7 +36,7 @@ from numpy cimport (
from pandas._libs.tslibs.util cimport get_c_string_buf_and_size
-cdef extern from "src/datetime/pd_datetime.h":
+cdef extern from "pandas/datetime/pd_datetime.h":
int cmp_npy_datetimestruct(npy_datetimestruct *a,
npy_datetimestruct *b)
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index 71550824525eb..536ae7ee4673b 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -83,10 +83,10 @@ from pandas._libs.tslibs.util cimport (
)
-cdef extern from "../src/headers/portable.h":
+cdef extern from "pandas/portable.h":
int getdigit_ascii(char c, int default) nogil
-cdef extern from "../src/parser/tokenizer.h":
+cdef extern from "pandas/parser/tokenizer.h":
double xstrtod(const char *p, char **q, char decimal, char sci, char tsep,
int skip_trailing, int *error, int *maybe_int)
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index c444e3b2bb71e..b0dac23c3b8e2 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -26,7 +26,7 @@ import cython
from pandas._libs.algos import is_monotonic
-cdef extern from "../src/skiplist.h":
+cdef extern from "pandas/skiplist.h":
ctypedef struct node_t:
node_t **next
int *width
diff --git a/pandas/_libs/window/meson.build b/pandas/_libs/window/meson.build
index 7d7c34a57c6a6..61719a35b2346 100644
--- a/pandas/_libs/window/meson.build
+++ b/pandas/_libs/window/meson.build
@@ -1,7 +1,7 @@
py.extension_module(
'aggregations',
['aggregations.pyx'],
- include_directories: [inc_np, '../src'],
+ include_directories: [inc_np, inc_pd],
dependencies: [py_dep],
subdir: 'pandas/_libs/window',
override_options : ['cython_language=cpp'],
@@ -11,7 +11,7 @@ py.extension_module(
py.extension_module(
'indexers',
['indexers.pyx'],
- include_directories: [inc_np],
+ include_directories: [inc_np, inc_pd],
dependencies: [py_dep],
subdir: 'pandas/_libs/window',
install: true
diff --git a/pandas/meson.build b/pandas/meson.build
index 491a08e6c0261..ab84fd688b762 100644
--- a/pandas/meson.build
+++ b/pandas/meson.build
@@ -7,8 +7,7 @@ incdir_numpy = run_command(py,
).stdout().strip()
inc_np = include_directories(incdir_numpy)
-klib_include = include_directories('_libs/src/klib')
-inc_datetime = include_directories('_libs/tslibs')
+inc_pd = include_directories('_libs/include')
fs.copyfile('__init__.py')
diff --git a/setup.py b/setup.py
index ee444f1aaeb85..e285299cfc05e 100755
--- a/setup.py
+++ b/setup.py
@@ -115,15 +115,14 @@ def initialize_options(self):
self._clean_trees = []
base = pjoin("pandas", "_libs", "src")
- tsbase = pjoin("pandas", "_libs", "tslibs", "src")
- dt = pjoin(tsbase, "datetime")
- util = pjoin("pandas", "util")
parser = pjoin(base, "parser")
- ujson_python = pjoin(base, "ujson", "python")
- ujson_lib = pjoin(base, "ujson", "lib")
+ vendored = pjoin(base, "vendored")
+ dt = pjoin(base, "datetime")
+ ujson_python = pjoin(vendored, "ujson", "python")
+ ujson_lib = pjoin(vendored, "ujson", "lib")
self._clean_exclude = [
- pjoin(dt, "np_datetime.c"),
- pjoin(dt, "np_datetime_strings.c"),
+ pjoin(vendored, "numpy", "datetime", "np_datetime.c"),
+ pjoin(vendored, "numpy", "datetime", "np_datetime_strings.c"),
pjoin(dt, "date_conversions.c"),
pjoin(parser, "tokenizer.c"),
pjoin(parser, "io.c"),
@@ -132,9 +131,8 @@ def initialize_options(self):
pjoin(ujson_python, "JSONtoObj.c"),
pjoin(ujson_lib, "ultrajsonenc.c"),
pjoin(ujson_lib, "ultrajsondec.c"),
- pjoin(util, "move.c"),
- pjoin(tsbase, "datetime", "pd_datetime.c"),
- pjoin("pandas", "_libs", "pd_parser.c"),
+ pjoin(dt, "pd_datetime.c"),
+ pjoin(parser, "pd_parser.c"),
]
for root, dirs, files in os.walk("pandas"):
@@ -431,19 +429,15 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
return pjoin("pandas", subdir, name + suffix)
-lib_depends = ["pandas/_libs/src/parse_helper.h"]
+lib_depends = ["pandas/_libs/include/pandas/parse_helper.h"]
-klib_include = ["pandas/_libs/src/klib"]
-
-tseries_includes = ["pandas/_libs/tslibs/src/datetime"]
tseries_depends = [
- "pandas/_libs/tslibs/src/datetime/pd_datetime.h",
+ "pandas/_libs/include/pandas/datetime/pd_datetime.h",
]
ext_data = {
"_libs.algos": {
"pyxfile": "_libs/algos",
- "include": klib_include,
"depends": _pxi_dep["algos"],
},
"_libs.arrays": {"pyxfile": "_libs/arrays"},
@@ -451,34 +445,32 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
"_libs.hashing": {"pyxfile": "_libs/hashing", "depends": []},
"_libs.hashtable": {
"pyxfile": "_libs/hashtable",
- "include": klib_include,
"depends": (
- ["pandas/_libs/src/klib/khash_python.h", "pandas/_libs/src/klib/khash.h"]
+ [
+ "pandas/_libs/include/pandas/vendored/klib/khash_python.h",
+ "pandas/_libs/include/pandas/vendored/klib/khash.h",
+ ]
+ _pxi_dep["hashtable"]
),
},
"_libs.index": {
"pyxfile": "_libs/index",
- "include": klib_include,
"depends": _pxi_dep["index"],
},
"_libs.indexing": {"pyxfile": "_libs/indexing"},
"_libs.internals": {"pyxfile": "_libs/internals"},
"_libs.interval": {
"pyxfile": "_libs/interval",
- "include": klib_include,
"depends": _pxi_dep["interval"],
},
- "_libs.join": {"pyxfile": "_libs/join", "include": klib_include},
+ "_libs.join": {"pyxfile": "_libs/join"},
"_libs.lib": {
"pyxfile": "_libs/lib",
"depends": lib_depends + tseries_depends,
- "include": klib_include, # due to tokenizer import
},
"_libs.missing": {"pyxfile": "_libs/missing", "depends": tseries_depends},
"_libs.parsers": {
"pyxfile": "_libs/parsers",
- "include": klib_include + ["pandas/_libs/src", "pandas/_libs"],
"depends": [
"pandas/_libs/src/parser/tokenizer.h",
"pandas/_libs/src/parser/io.h",
@@ -500,7 +492,6 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
"_libs.tslibs.conversion": {
"pyxfile": "_libs/tslibs/conversion",
"depends": tseries_depends,
- "include": klib_include,
},
"_libs.tslibs.fields": {
"pyxfile": "_libs/tslibs/fields",
@@ -510,17 +501,13 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
"_libs.tslibs.np_datetime": {
"pyxfile": "_libs/tslibs/np_datetime",
"depends": tseries_depends,
- "includes": tseries_includes,
},
"_libs.tslibs.offsets": {
"pyxfile": "_libs/tslibs/offsets",
"depends": tseries_depends,
- "includes": tseries_includes,
},
"_libs.tslibs.parsing": {
"pyxfile": "_libs/tslibs/parsing",
- "include": tseries_includes + klib_include,
- "depends": ["pandas/_libs/src/parser/tokenizer.h"],
"sources": ["pandas/_libs/src/parser/tokenizer.c"],
},
"_libs.tslibs.period": {
@@ -537,7 +524,6 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
},
"_libs.tslibs.timestamps": {
"pyxfile": "_libs/tslibs/timestamps",
- "include": tseries_includes,
"depends": tseries_depends,
},
"_libs.tslibs.timezones": {"pyxfile": "_libs/tslibs/timezones"},
@@ -554,7 +540,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
"pyxfile": "_libs/window/aggregations",
"language": "c++",
"suffix": ".cpp",
- "depends": ["pandas/_libs/src/skiplist.h"],
+ "depends": ["pandas/_libs/include/pandas/skiplist.h"],
},
"_libs.window.indexers": {"pyxfile": "_libs/window/indexers"},
"_libs.writers": {"pyxfile": "_libs/writers"},
@@ -571,8 +557,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
sources.extend(data.get("sources", []))
- include = data.get("include", [])
- include.append(numpy.get_include())
+ include = ["pandas/_libs/include", numpy.get_include()]
undef_macros = []
@@ -612,24 +597,22 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
ujson_ext = Extension(
"pandas._libs.json",
depends=[
- "pandas/_libs/src/ujson/lib/ultrajson.h",
- "pandas/_libs/tslibs/src/datetime/pd_datetime.h",
+ "pandas/_libs/include/pandas/vendored/ujson/lib/ultrajson.h",
+ "pandas/_libs/include/pandas/datetime/pd_datetime.h",
],
sources=(
[
- "pandas/_libs/src/ujson/python/ujson.c",
- "pandas/_libs/src/ujson/python/objToJSON.c",
- "pandas/_libs/src/ujson/python/JSONtoObj.c",
- "pandas/_libs/src/ujson/lib/ultrajsonenc.c",
- "pandas/_libs/src/ujson/lib/ultrajsondec.c",
+ "pandas/_libs/src/vendored/ujson/python/ujson.c",
+ "pandas/_libs/src/vendored/ujson/python/objToJSON.c",
+ "pandas/_libs/src/vendored/ujson/python/JSONtoObj.c",
+ "pandas/_libs/src/vendored/ujson/lib/ultrajsonenc.c",
+ "pandas/_libs/src/vendored/ujson/lib/ultrajsondec.c",
]
),
include_dirs=[
- "pandas/_libs/src/ujson/python",
- "pandas/_libs/src/ujson/lib",
+ "pandas/_libs/include",
numpy.get_include(),
- ]
- + tseries_includes,
+ ],
extra_compile_args=(extra_compile_args),
extra_link_args=extra_link_args,
define_macros=macros,
@@ -647,14 +630,14 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
depends=["pandas/_libs/tslibs/datetime/pd_datetime.h"],
sources=(
[
- "pandas/_libs/tslibs/src/datetime/np_datetime.c",
- "pandas/_libs/tslibs/src/datetime/np_datetime_strings.c",
- "pandas/_libs/tslibs/src/datetime/date_conversions.c",
- "pandas/_libs/tslibs/src/datetime/pd_datetime.c",
+ "pandas/_libs/src/vendored/numpy/datetime/np_datetime.c",
+ "pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c",
+ "pandas/_libs/src/datetime/date_conversions.c",
+ "pandas/_libs/src/datetime/pd_datetime.c",
]
),
- include_dirs=tseries_includes
- + [
+ include_dirs=[
+ "pandas/_libs/include",
numpy.get_include(),
],
extra_compile_args=(extra_compile_args),
@@ -671,16 +654,16 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
# pd_datetime
pd_parser_ext = Extension(
"pandas._libs.pandas_parser",
- depends=["pandas/_libs/pd_parser.h"],
+ depends=["pandas/_libs/include/pandas/parser/pd_parser.h"],
sources=(
[
"pandas/_libs/src/parser/tokenizer.c",
"pandas/_libs/src/parser/io.c",
- "pandas/_libs/pd_parser.c",
+ "pandas/_libs/src/parser/pd_parser.c",
]
),
include_dirs=[
- "pandas/_libs/src/klib",
+ "pandas/_libs/include",
],
extra_compile_args=(extra_compile_args),
extra_link_args=extra_link_args,
| This puts all source files in `pandas/_libs/src` and all header files in `pandas/_libs/include` This simplifies our includes, letting us do them in an "absolute" way, while also making it clear which headers/sources were vendored | https://api.github.com/repos/pandas-dev/pandas/pulls/53346 | 2023-05-22T23:46:09Z | 2023-05-31T17:16:28Z | 2023-05-31T17:16:28Z | 2023-05-31T18:45:11Z |
BUG: Correct .type for pyarrow.map_ and pyarrow.struct types | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 52d2730195a56..cec201db7e216 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -25,6 +25,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
+- Bug in :class:`.arrays.ArrowExtensionArray` incorrectly assigning ``dict`` instead of ``list`` for ``.type`` with ``pyarrow.map_`` and raising a ``NotImplementedError`` with ``pyarrow.struct`` (:issue:`53328`)
- Bug in :func:`api.interchange.from_dataframe` was raising ``IndexError`` on empty categorical data (:issue:`53077`)
- Bug in :func:`api.interchange.from_dataframe` was returning :class:`DataFrame`'s of incorrect sizes when called on slices (:issue:`52824`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on bitmasks (:issue:`49888`)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index e6c1c70a2aff5..2d0ec66dbc9cb 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -2053,6 +2053,8 @@ def type(self):
elif pa.types.is_list(pa_type) or pa.types.is_large_list(pa_type):
return list
elif pa.types.is_map(pa_type):
+ return list
+ elif pa.types.is_struct(pa_type):
return dict
elif pa.types.is_null(pa_type):
# TODO: None? pd.NA? pa.null?
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 1b0786bcd5d2e..9129e84700a55 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -1570,7 +1570,8 @@ def test_mode_dropna_false_mode_na(data):
[pa.large_string(), str],
[pa.list_(pa.int64()), list],
[pa.large_list(pa.int64()), list],
- [pa.map_(pa.string(), pa.int64()), dict],
+ [pa.map_(pa.string(), pa.int64()), list],
+ [pa.struct([("f1", pa.int8()), ("f2", pa.string())]), dict],
[pa.dictionary(pa.int64(), pa.int64()), CategoricalDtypeType],
],
)
| - [ ] closes #53328 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53344 | 2023-05-22T21:42:23Z | 2023-05-24T01:55:39Z | 2023-05-24T01:55:39Z | 2023-05-24T02:00:49Z |
REF: Use np.result_type instead of np.find_common_type | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 37c1fa76fbbcf..768265a5ce621 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -32,7 +32,10 @@
from pandas.util._decorators import doc
from pandas.util._exceptions import find_stack_level
-from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
+from pandas.core.dtypes.cast import (
+ construct_1d_object_array_from_listlike,
+ np_find_common_type,
+)
from pandas.core.dtypes.common import (
ensure_float64,
ensure_object,
@@ -518,7 +521,7 @@ def f(c, v):
f = np.in1d
else:
- common = np.find_common_type([values.dtype, comps_array.dtype], [])
+ common = np_find_common_type(values.dtype, comps_array.dtype)
values = values.astype(common, copy=False)
comps_array = comps_array.astype(common, copy=False)
f = htable.ismember
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index e7a6692807685..c863e5bb4dbd4 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1328,6 +1328,32 @@ def common_dtype_categorical_compat(
return dtype
+def np_find_common_type(*dtypes: np.dtype) -> np.dtype:
+ """
+ np.find_common_type implementation pre-1.25 deprecation using np.result_type
+ https://github.com/pandas-dev/pandas/pull/49569#issuecomment-1308300065
+
+ Parameters
+ ----------
+ dtypes : np.dtypes
+
+ Returns
+ -------
+ np.dtype
+ """
+ try:
+ common_dtype = np.result_type(*dtypes)
+ if common_dtype.kind in "mMSU":
+ # NumPy promotion currently (1.25) misbehaves for for times and strings,
+ # so fall back to object (find_common_dtype did unless there
+ # was only one dtype)
+ common_dtype = np.dtype("O")
+
+ except TypeError:
+ common_dtype = np.dtype("O")
+ return common_dtype
+
+
@overload
def find_common_type(types: list[np.dtype]) -> np.dtype:
...
@@ -1395,7 +1421,7 @@ def find_common_type(types):
if t.kind in "iufc":
return np.dtype("object")
- return np.find_common_type(types, [])
+ return np_find_common_type(*types)
def construct_2d_arraylike_from_scalar(
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index 4a25c3541a398..cba7c44a219bf 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -17,6 +17,7 @@
from pandas.core.dtypes.cast import (
common_dtype_categorical_compat,
find_common_type,
+ np_find_common_type,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import (
@@ -156,11 +157,9 @@ def _get_result_dtype(
target_dtype = np.dtype(object)
kinds = {"o"}
else:
- # Argument 1 to "list" has incompatible type "Set[Union[ExtensionDtype,
- # Any]]"; expected "Iterable[Union[dtype[Any], None, Type[Any],
- # _SupportsDType[dtype[Any]], str, Tuple[Any, Union[SupportsIndex,
- # Sequence[SupportsIndex]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
- target_dtype = np.find_common_type(list(dtypes), []) # type: ignore[arg-type]
+ # error: Argument 1 to "np_find_common_type" has incompatible type
+ # "*Set[Union[ExtensionDtype, Any]]"; expected "dtype[Any]"
+ target_dtype = np_find_common_type(*dtypes) # type: ignore[arg-type]
return any_ea, kinds, target_dtype
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index a3481cbe9eae1..e6c1c70a2aff5 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -1921,6 +1921,8 @@ def _subtype_with_str(self):
def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
# TODO for now only handle SparseDtypes and numpy dtypes => extend
# with other compatible extension dtypes
+ from pandas.core.dtypes.cast import np_find_common_type
+
if any(
isinstance(x, ExtensionDtype) and not isinstance(x, SparseDtype)
for x in dtypes
@@ -1943,8 +1945,8 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
stacklevel=find_stack_level(),
)
- np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes]
- return SparseDtype(np.find_common_type(np_dtypes, []), fill_value=fill_value)
+ np_dtypes = (x.subtype if isinstance(x, SparseDtype) else x for x in dtypes)
+ return SparseDtype(np_find_common_type(*np_dtypes), fill_value=fill_value)
@register_extension_dtype
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 75eaaa80a9961..098a78fc54b71 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -29,6 +29,7 @@
ensure_dtype_can_hold_na,
find_common_type,
infer_dtype_from_scalar,
+ np_find_common_type,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
@@ -1409,7 +1410,7 @@ def concat_arrays(to_concat: list) -> ArrayLike:
target_dtype = to_concat_no_proxy[0].dtype
elif all(x.kind in "iub" and isinstance(x, np.dtype) for x in dtypes):
# GH#42092
- target_dtype = np.find_common_type(list(dtypes), [])
+ target_dtype = np_find_common_type(*dtypes)
else:
target_dtype = find_common_type([arr.dtype for arr in to_concat_no_proxy])
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 4f884afcb1a90..bbce40727c669 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -997,9 +997,7 @@ def test_maybe_convert_objects_itemsize(self, data0, data1):
data = [data0, data1]
arr = np.array(data, dtype="object")
- common_kind = np.find_common_type(
- [type(data0), type(data1)], scalar_types=[]
- ).kind
+ common_kind = np.result_type(type(data0), type(data1)).kind
kind0 = "python" if not hasattr(data0, "dtype") else data0.dtype.kind
kind1 = "python" if not hasattr(data1, "dtype") else data1.dtype.kind
if kind0 != "python" and kind1 != "python":
| - [ ] closes #53236 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53343 | 2023-05-22T20:37:02Z | 2023-05-23T20:35:09Z | 2023-05-23T20:35:09Z | 2023-05-23T22:05:06Z |
Update timedeltas.pyx | diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 518a79c7c281a..047b5e861da2c 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -1592,7 +1592,7 @@ cdef class _Timedelta(timedelta):
def as_unit(self, str unit, bint round_ok=True):
"""
- Convert the underlying int64 representaton to the given unit.
+ Convert the underlying int64 representation to the given unit.
Parameters
----------
| Typo : representaton --> representation | https://api.github.com/repos/pandas-dev/pandas/pulls/53342 | 2023-05-22T19:39:24Z | 2023-05-22T23:22:16Z | 2023-05-22T23:22:16Z | 2023-05-23T07:22:08Z |
Upload nightlies to new location | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 9ebe147008451..541b36d9b4c1d 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -337,7 +337,7 @@ jobs:
run: |
python --version
python -m pip install --upgrade pip setuptools wheel
- python -m pip install --pre --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
+ python -m pip install --pre --extra-index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple numpy
python -m pip install git+https://github.com/nedbat/coveragepy.git
python -m pip install versioneer[toml]
python -m pip install python-dateutil pytz cython hypothesis>=6.46.1 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-cov pytest-asyncio>=0.17
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 0a508a8b1701f..cdc4fd18995da 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -156,7 +156,7 @@ jobs:
PANDAS_STAGING_UPLOAD_TOKEN: ${{ secrets.PANDAS_STAGING_UPLOAD_TOKEN }}
PANDAS_NIGHTLY_UPLOAD_TOKEN: ${{ secrets.PANDAS_NIGHTLY_UPLOAD_TOKEN }}
# trigger an upload to
- # https://anaconda.org/scipy-wheels-nightly/pandas
+ # https://anaconda.org/scientific-python-nightly-wheels/pandas
# for cron jobs or "Run workflow" (restricted to main branch).
# Tags will upload to
# https://anaconda.org/multibuild-wheels-staging/pandas
diff --git a/ci/upload_wheels.sh b/ci/upload_wheels.sh
index f760621ea0e6b..e57e9b01b9830 100644
--- a/ci/upload_wheels.sh
+++ b/ci/upload_wheels.sh
@@ -10,7 +10,7 @@ set_upload_vars() {
export ANACONDA_UPLOAD="true"
elif [[ "$IS_SCHEDULE_DISPATCH" == "true" ]]; then
echo scheduled or dispatched event
- export ANACONDA_ORG="scipy-wheels-nightly"
+ export ANACONDA_ORG="scientific-python-nightly-wheels"
export TOKEN="$PANDAS_NIGHTLY_UPLOAD_TOKEN"
export ANACONDA_UPLOAD="true"
else
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 90a65e2790c29..f4c76c3493fa2 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -201,9 +201,9 @@ Installing a nightly build is the quickest way to:
* Try a new feature that will be shipped in the next release (that is, a feature from a pull-request that was recently merged to the main branch).
* Check whether a bug you encountered has been fixed since the last release.
-You can install the nightly build of pandas using the scipy-wheels-nightly index from the PyPI registry of anaconda.org with the following command::
+You can install the nightly build of pandas using the scientific-python-nightly-wheels index from the PyPI registry of anaconda.org with the following command::
- pip install --pre --extra-index https://pypi.anaconda.org/scipy-wheels-nightly/simple pandas
+ pip install --pre --extra-index https://pypi.anaconda.org/scientific-python-nightly-wheels/simple pandas
Note that first uninstalling pandas might be required to be able to install nightly builds::
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53341 | 2023-05-22T18:07:05Z | 2023-06-08T23:09:35Z | 2023-06-08T23:09:35Z | 2023-06-08T23:10:43Z |
DEPR: int slicing always positional | diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index ac7e383d6d7ff..27d7e63f72111 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -436,7 +436,7 @@ at the new values.
# interpolate at new_index
new_index = ser.index.union(pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75]))
interp_s = ser.reindex(new_index).interpolate(method="pchip")
- interp_s[49:51]
+ interp_s.loc[49:51]
.. _scipy: https://scipy.org/
.. _documentation: https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation
diff --git a/doc/source/whatsnew/v0.13.0.rst b/doc/source/whatsnew/v0.13.0.rst
index 2e086f560bd53..bfabfb1a27e73 100644
--- a/doc/source/whatsnew/v0.13.0.rst
+++ b/doc/source/whatsnew/v0.13.0.rst
@@ -343,6 +343,7 @@ Float64Index API change
Slicing is ALWAYS on the values of the index, for ``[],ix,loc`` and ALWAYS positional with ``iloc``
.. ipython:: python
+ :okwarning:
s[2:4]
s.loc[2:4]
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 64948e78676d4..f8207a0c1afb3 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -552,6 +552,7 @@ Other Deprecations
- Deprecated the "method" and "limit" keywords in ``ExtensionArray.fillna``, implement and use ``pad_or_backfill`` instead (:issue:`53621`)
- Deprecated the "method" and "limit" keywords on :meth:`Series.fillna`, :meth:`DataFrame.fillna`, :meth:`SeriesGroupBy.fillna`, :meth:`DataFrameGroupBy.fillna`, and :meth:`Resampler.fillna`, use ``obj.bfill()`` or ``obj.ffill()`` instead (:issue:`53394`)
- Deprecated the ``method`` and ``limit`` keywords in :meth:`DataFrame.replace` and :meth:`Series.replace` (:issue:`33302`)
+- Deprecated the behavior of :meth:`Series.__getitem__`, :meth:`Series.__setitem__`, :meth:`DataFrame.__getitem__`, :meth:`DataFrame.__setitem__` with an integer slice on objects with a floating-dtype index, in a future version this will be treated as *positional* indexing (:issue:`49612`)
- Deprecated the use of non-supported datetime64 and timedelta64 resolutions with :func:`pandas.array`. Supported resolutions are: "s", "ms", "us", "ns" resolutions (:issue:`53058`)
- Deprecated values "pad", "ffill", "bfill", "backfill" for :meth:`Series.interpolate` and :meth:`DataFrame.interpolate`, use ``obj.ffill()`` or ``obj.bfill()`` instead (:issue:`53581`)
- Deprecated the behavior of :meth:`Index.argmax`, :meth:`Index.argmin`, :meth:`Series.argmax`, :meth:`Series.argmin` with either all-NAs and skipna=True or any-NAs and skipna=False returning -1; in a future version this will raise ``ValueError`` (:issue:`33941`, :issue:`33942`)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 80b4bcc583fdb..e5c940df93a1c 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4212,16 +4212,30 @@ def _convert_slice_indexer(self, key: slice, kind: Literal["loc", "getitem"]):
# potentially cast the bounds to integers
start, stop, step = key.start, key.stop, key.step
+ # figure out if this is a positional indexer
+ is_index_slice = is_valid_positional_slice(key)
+
# TODO(GH#50617): once Series.__[gs]etitem__ is removed we should be able
# to simplify this.
if lib.is_np_dtype(self.dtype, "f"):
# We always treat __getitem__ slicing as label-based
# translate to locations
+ if kind == "getitem" and is_index_slice and not start == stop and step != 0:
+ # exclude step=0 from the warning because it will raise anyway
+ # start/stop both None e.g. [:] or [::-1] won't change.
+ # exclude start==stop since it will be empty either way, or
+ # will be [:] or [::-1] which won't change
+ warnings.warn(
+ # GH#49612
+ "The behavior of obj[i:j] with a float-dtype index is "
+ "deprecated. In a future version, this will be treated as "
+ "positional instead of label-based. For label-based slicing, "
+ "use obj.loc[i:j] instead",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.slice_indexer(start, stop, step)
- # figure out if this is a positional indexer
- is_index_slice = is_valid_positional_slice(key)
-
if kind == "getitem":
# called from the getitem slicers, validate that we are in fact integers
if is_index_slice:
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index ea978fe68b1ad..288aa1af746b6 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -755,7 +755,9 @@ def test_getitem_setitem_float_labels(self, using_array_manager):
tm.assert_frame_equal(result, expected)
df.loc[1:2] = 0
- result = df[1:2]
+ msg = r"The behavior of obj\[i:j\] with a float-dtype index"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df[1:2]
assert (result == 0).all().all()
# #2727
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py
index 1c91b69597d78..c9fbf95751dfe 100644
--- a/pandas/tests/indexing/test_floats.py
+++ b/pandas/tests/indexing/test_floats.py
@@ -488,8 +488,12 @@ def test_floating_misc(self, indexer_sl):
for fancy_idx in [[5, 0], np.array([5, 0])]:
tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
+ warn = FutureWarning if indexer_sl is tm.setitem else None
+ msg = r"The behavior of obj\[i:j\] with a float-dtype index"
+
# all should return the same as we are slicing 'the same'
- result1 = indexer_sl(s)[2:5]
+ with tm.assert_produces_warning(warn, match=msg):
+ result1 = indexer_sl(s)[2:5]
result2 = indexer_sl(s)[2.0:5.0]
result3 = indexer_sl(s)[2.0:5]
result4 = indexer_sl(s)[2.1:5]
@@ -498,7 +502,8 @@ def test_floating_misc(self, indexer_sl):
tm.assert_series_equal(result1, result4)
expected = Series([1, 2], index=[2.5, 5.0])
- result = indexer_sl(s)[2:5]
+ with tm.assert_produces_warning(warn, match=msg):
+ result = indexer_sl(s)[2:5]
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py
index 3b099720dcdf2..99e8b9076fcc3 100644
--- a/pandas/tests/series/methods/test_interpolate.py
+++ b/pandas/tests/series/methods/test_interpolate.py
@@ -129,7 +129,7 @@ def test_interpolate_cubicspline(self):
new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(
float
)
- result = ser.reindex(new_index).interpolate(method="cubicspline")[1:3]
+ result = ser.reindex(new_index).interpolate(method="cubicspline").loc[1:3]
tm.assert_series_equal(result, expected)
@td.skip_if_no_scipy
@@ -142,7 +142,7 @@ def test_interpolate_pchip(self):
).astype(float)
interp_s = ser.reindex(new_index).interpolate(method="pchip")
# does not blow up, GH5977
- interp_s[49:51]
+ interp_s.loc[49:51]
@td.skip_if_no_scipy
def test_interpolate_akima(self):
@@ -157,7 +157,7 @@ def test_interpolate_akima(self):
float
)
interp_s = ser.reindex(new_index).interpolate(method="akima")
- tm.assert_series_equal(interp_s[1:3], expected)
+ tm.assert_series_equal(interp_s.loc[1:3], expected)
# interpolate at new_index where `der` is a non-zero int
expected = Series(
@@ -168,7 +168,7 @@ def test_interpolate_akima(self):
float
)
interp_s = ser.reindex(new_index).interpolate(method="akima", der=1)
- tm.assert_series_equal(interp_s[1:3], expected)
+ tm.assert_series_equal(interp_s.loc[1:3], expected)
@td.skip_if_no_scipy
def test_interpolate_piecewise_polynomial(self):
@@ -183,7 +183,7 @@ def test_interpolate_piecewise_polynomial(self):
float
)
interp_s = ser.reindex(new_index).interpolate(method="piecewise_polynomial")
- tm.assert_series_equal(interp_s[1:3], expected)
+ tm.assert_series_equal(interp_s.loc[1:3], expected)
@td.skip_if_no_scipy
def test_interpolate_from_derivatives(self):
@@ -198,7 +198,7 @@ def test_interpolate_from_derivatives(self):
float
)
interp_s = ser.reindex(new_index).interpolate(method="from_derivatives")
- tm.assert_series_equal(interp_s[1:3], expected)
+ tm.assert_series_equal(interp_s.loc[1:3], expected)
@pytest.mark.parametrize(
"kwargs",
@@ -218,7 +218,7 @@ def test_interpolate_corners(self, kwargs):
def test_interpolate_index_values(self):
s = Series(np.nan, index=np.sort(np.random.default_rng(2).random(30)))
- s[::3] = np.random.default_rng(2).standard_normal(10)
+ s.loc[::3] = np.random.default_rng(2).standard_normal(10)
vals = s.index.values.astype(float)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
We've gone back and forth on this a couple times (#45324, #49869 would have done this as a breaking change in 2.0). | https://api.github.com/repos/pandas-dev/pandas/pulls/53338 | 2023-05-22T16:14:16Z | 2023-08-04T21:26:14Z | 2023-08-04T21:26:14Z | 2023-08-04T21:27:11Z |
DOC: Fixing EX01 - Added examples | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 4eecee4be4731..64c5b735fdc8d 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -170,8 +170,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.Period.asfreq \
pandas.Period.now \
pandas.arrays.PeriodArray \
- pandas.arrays.IntervalArray.from_arrays \
- pandas.arrays.IntervalArray.to_tuples \
pandas.Int8Dtype \
pandas.Int16Dtype \
pandas.Int32Dtype \
@@ -181,8 +179,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.UInt32Dtype \
pandas.UInt64Dtype \
pandas.NA \
- pandas.Float32Dtype \
- pandas.Float64Dtype \
pandas.CategoricalDtype.categories \
pandas.CategoricalDtype.ordered \
pandas.Categorical.dtype \
@@ -258,9 +254,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.util.hash_pandas_object \
pandas_object \
pandas.api.interchange.from_dataframe \
- pandas.Index.T \
- pandas.Index.memory_usage \
- pandas.Index.copy \
pandas.Index.drop \
pandas.Index.identical \
pandas.Index.insert \
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index c268b25bf4a59..bd3c03f9218d4 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -134,6 +134,20 @@ class FloatingArray(NumericArray):
Methods
-------
None
+
+Examples
+--------
+For Float32Dtype:
+
+>>> ser = pd.Series([2.25, pd.NA], dtype=pd.Float32Dtype())
+>>> ser.dtype
+Float32Dtype()
+
+For Float64Dtype:
+
+>>> ser = pd.Series([2.25, pd.NA], dtype=pd.Float64Dtype())
+>>> ser.dtype
+Float64Dtype()
"""
# create the Dtype
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 2303f8334c07c..2842d8267b7c6 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -509,6 +509,8 @@ def from_breaks(
"name": "",
"examples": textwrap.dedent(
"""\
+ Examples
+ --------
>>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3])
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
@@ -1635,9 +1637,8 @@ def __arrow_array__(self, type=None):
return pyarrow.ExtensionArray.from_storage(interval_type, storage_array)
- _interval_shared_docs[
- "to_tuples"
- ] = """
+ _interval_shared_docs["to_tuples"] = textwrap.dedent(
+ """
Return an %(return_type)s of tuples of the form (left, right).
Parameters
@@ -1651,9 +1652,27 @@ def __arrow_array__(self, type=None):
tuples: %(return_type)s
%(examples)s\
"""
+ )
@Appender(
- _interval_shared_docs["to_tuples"] % {"return_type": "ndarray", "examples": ""}
+ _interval_shared_docs["to_tuples"]
+ % {
+ "return_type": "ndarray",
+ "examples": textwrap.dedent(
+ """\
+
+ Examples
+ --------
+ >>> idx = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
+ >>> idx
+ <IntervalArray>
+ [(0, 1], (1, 2]]
+ Length: 2, dtype: interval[int64, right]
+ >>> idx.to_tuples()
+ array([(0, 1), (1, 2)], dtype=object)
+ """
+ ),
+ }
)
def to_tuples(self, na_tuple: bool = True) -> np.ndarray:
tuples = com.asarray_tuplesafe(zip(self._left, self._right))
diff --git a/pandas/core/base.py b/pandas/core/base.py
index d939c0d454de8..0d99118d25e96 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -300,6 +300,8 @@ def transpose(self, *args, **kwargs) -> Self:
Examples
--------
+ For Series:
+
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
@@ -311,6 +313,12 @@ def transpose(self, *args, **kwargs) -> Self:
1 Bear
2 Cow
dtype: object
+
+ For Index:
+
+ >>> idx = pd.Index([1, 2, 3])
+ >>> idx.T
+ Index([1, 2, 3], dtype='int64')
""",
)
@@ -1088,6 +1096,12 @@ def _memory_usage(self, deep: bool = False) -> int:
-----
Memory usage does not include memory consumed by elements that
are not components of the array if deep=False or if used on PyPy
+
+ Examples
+ --------
+ >>> idx = pd.Index([1, 2, 3])
+ >>> idx.memory_usage()
+ 24
"""
if hasattr(self.array, "memory_usage"):
return self.array.memory_usage( # pyright: ignore[reportGeneralTypeIssues]
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index e7d975068dd70..174c6625fb779 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -1221,6 +1221,13 @@ def copy(
-----
In most cases, there should be no functional difference from using
``deep``, but if ``deep`` is passed it will attempt to deepcopy.
+
+ Examples
+ --------
+ >>> idx = pd.Index(['a', 'b', 'c'])
+ >>> new_idx = idx.copy()
+ >>> idx is new_idx
+ False
"""
name = self._validate_names(name=name, deep=deep)[0]
| - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
Towards https://github.com/pandas-dev/pandas/issues/37875
| https://api.github.com/repos/pandas-dev/pandas/pulls/53336 | 2023-05-22T15:16:33Z | 2023-05-23T10:00:20Z | 2023-05-23T10:00:20Z | 2023-05-23T10:00:35Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.