title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
DOC: Add a reference to window.rst in computation.rst | diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst
index f05eb9cc40402..17d1809638d61 100644
--- a/doc/source/user_guide/computation.rst
+++ b/doc/source/user_guide/computation.rst
@@ -205,3 +205,10 @@ parameter:
- ``min`` : lowest rank in the group
- ``max`` : highest rank in the group
- ``first`` : ranks assigned in the order they appear in the array
+
+.. _computation.windowing:
+
+Windowing functions
+~~~~~~~~~~~~~~~~~~~
+
+See :ref:`the window operations user guide <window.overview>` for an overview of windowing functions.
| xref https://github.com/pandas-dev/pandas/pull/37575#issuecomment-727235030
| https://api.github.com/repos/pandas-dev/pandas/pulls/37855 | 2020-11-14T21:52:54Z | 2020-11-15T17:25:42Z | 2020-11-15T17:25:42Z | 2020-11-15T19:44:11Z |
CLN: Another unused script | diff --git a/test.bat b/test.bat
deleted file mode 100644
index e07c84f257a69..0000000000000
--- a/test.bat
+++ /dev/null
@@ -1,3 +0,0 @@
-:: test on windows
-
-pytest --skip-slow --skip-network pandas -n 2 -r sxX --strict %*
| xref https://github.com/pandas-dev/pandas/pull/37825
Another script that looks unused and undocumented
| https://api.github.com/repos/pandas-dev/pandas/pulls/37854 | 2020-11-14T21:46:32Z | 2020-11-17T17:09:16Z | 2020-11-17T17:09:16Z | 2020-11-17T17:09:20Z |
CLN: indexing plane_indexer -> pi | diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index e0bf43d3a0140..a8951e342e0da 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1654,8 +1654,8 @@ def _setitem_with_indexer_split_path(self, indexer, value):
# Ensure we have something we can iterate over
ilocs = self._ensure_iterable_column_indexer(indexer[1])
- plane_indexer = indexer[:1]
- lplane_indexer = length_of_indexer(plane_indexer[0], self.obj.index)
+ pi = indexer[0]
+ lplane_indexer = length_of_indexer(pi, self.obj.index)
# lplane_indexer gives the expected length of obj[indexer[0]]
if len(ilocs) == 1:
@@ -1686,14 +1686,10 @@ def _setitem_with_indexer_split_path(self, indexer, value):
elif np.ndim(value) == 2:
self._setitem_with_indexer_2d_value(indexer, value)
- elif (
- len(ilocs) == 1
- and lplane_indexer == len(value)
- and not is_scalar(plane_indexer[0])
- ):
+ elif len(ilocs) == 1 and lplane_indexer == len(value) and not is_scalar(pi):
# we have an equal len list/ndarray
# We only get here with len(ilocs) == 1
- self._setitem_single_column(ilocs[0], value, plane_indexer)
+ self._setitem_single_column(ilocs[0], value, pi)
elif lplane_indexer == 0 and len(value) == len(self.obj.index):
# We get here in one case via .loc with a all-False mask
@@ -1708,7 +1704,7 @@ def _setitem_with_indexer_split_path(self, indexer, value):
)
for loc, v in zip(ilocs, value):
- self._setitem_single_column(loc, v, plane_indexer)
+ self._setitem_single_column(loc, v, pi)
else:
if isinstance(indexer[0], np.ndarray) and indexer[0].ndim > 2:
@@ -1716,12 +1712,12 @@ def _setitem_with_indexer_split_path(self, indexer, value):
# scalar value
for loc in ilocs:
- self._setitem_single_column(loc, value, plane_indexer)
+ self._setitem_single_column(loc, value, pi)
def _setitem_with_indexer_2d_value(self, indexer, value):
# We get here with np.ndim(value) == 2, excluding DataFrame,
# which goes through _setitem_with_indexer_frame_value
- plane_indexer = indexer[:1]
+ pi = indexer[0]
ilocs = self._ensure_iterable_column_indexer(indexer[1])
@@ -1734,13 +1730,13 @@ def _setitem_with_indexer_2d_value(self, indexer, value):
for i, loc in enumerate(ilocs):
# setting with a list, re-coerces
- self._setitem_single_column(loc, value[:, i].tolist(), plane_indexer)
+ self._setitem_single_column(loc, value[:, i].tolist(), pi)
def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame"):
ilocs = self._ensure_iterable_column_indexer(indexer[1])
sub_indexer = list(indexer)
- plane_indexer = indexer[:1]
+ pi = indexer[0]
multiindex_indexer = isinstance(self.obj.columns, ABCMultiIndex)
@@ -1761,7 +1757,7 @@ def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame"):
else:
val = np.nan
- self._setitem_single_column(loc, val, plane_indexer)
+ self._setitem_single_column(loc, val, pi)
elif not unique_cols:
raise ValueError("Setting with non-unique columns is not allowed.")
@@ -1777,10 +1773,18 @@ def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame"):
else:
val = np.nan
- self._setitem_single_column(loc, val, plane_indexer)
+ self._setitem_single_column(loc, val, pi)
def _setitem_single_column(self, loc: int, value, plane_indexer):
- # positional setting on column loc
+ """
+
+ Parameters
+ ----------
+ loc : int
+ Indexer for column position
+ plane_indexer : int, slice, listlike[int]
+ The indexer we use for setitem along axis=0.
+ """
pi = plane_indexer
ser = self.obj._ixs(loc, axis=1)
@@ -1790,15 +1794,12 @@ def _setitem_single_column(self, loc: int, value, plane_indexer):
# which means essentially reassign to the columns of a
# multi-dim object
# GH#6149 (null slice), GH#10408 (full bounds)
- if isinstance(pi, tuple) and all(
- com.is_null_slice(idx) or com.is_full_slice(idx, len(self.obj))
- for idx in pi
- ):
+ if com.is_null_slice(pi) or com.is_full_slice(pi, len(self.obj)):
ser = value
else:
# set the item, possibly having a dtype change
ser = ser.copy()
- ser._mgr = ser._mgr.setitem(indexer=pi, value=value)
+ ser._mgr = ser._mgr.setitem(indexer=(pi,), value=value)
ser._maybe_update_cacher(clear=True)
# reset the sliced object if unique
| We know plane_indexer is a 1-tuple, can simplify a bit. | https://api.github.com/repos/pandas-dev/pandas/pulls/37853 | 2020-11-14T21:30:51Z | 2020-11-15T17:21:52Z | 2020-11-15T17:21:52Z | 2020-11-15T18:15:00Z |
making namespace usage more consistent | diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 836b1dcddf0dd..f4f258b559939 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -11,7 +11,17 @@
import pytest
import pandas as pd
-from pandas import Index, Int64Index, Series, Timedelta, TimedeltaIndex, array
+from pandas import (
+ Float64Index,
+ Index,
+ Int64Index,
+ RangeIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ UInt64Index,
+ array,
+)
import pandas._testing as tm
from pandas.core import ops
@@ -43,7 +53,7 @@ def adjust_negative_zero(zero, expected):
# List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex]
# See GH#29725
ser_or_index: List[Any] = [Series, Index]
-lefts: List[Any] = [pd.RangeIndex(10, 40, 10)]
+lefts: List[Any] = [RangeIndex(10, 40, 10)]
lefts.extend(
[
cls([10, 20, 30], dtype=dtype)
@@ -364,7 +374,7 @@ def test_divmod_zero(self, zero, numeric_idx):
@pytest.mark.parametrize("op", [operator.truediv, operator.floordiv])
def test_div_negative_zero(self, zero, numeric_idx, op):
# Check that -1 / -0.0 returns np.inf, not -np.inf
- if isinstance(numeric_idx, pd.UInt64Index):
+ if isinstance(numeric_idx, UInt64Index):
return
idx = numeric_idx - 3
@@ -634,7 +644,7 @@ def test_mul_int_array(self, numeric_idx):
result = idx * np.array(5, dtype="int64")
tm.assert_index_equal(result, idx * 5)
- arr_dtype = "uint64" if isinstance(idx, pd.UInt64Index) else "int64"
+ arr_dtype = "uint64" if isinstance(idx, UInt64Index) else "int64"
result = idx * np.arange(5, dtype=arr_dtype)
tm.assert_index_equal(result, didx)
@@ -642,7 +652,7 @@ def test_mul_int_series(self, numeric_idx):
idx = numeric_idx
didx = idx * idx
- arr_dtype = "uint64" if isinstance(idx, pd.UInt64Index) else "int64"
+ arr_dtype = "uint64" if isinstance(idx, UInt64Index) else "int64"
result = idx * Series(np.arange(5, dtype=arr_dtype))
tm.assert_series_equal(result, Series(didx))
@@ -657,7 +667,7 @@ def test_mul_float_series(self, numeric_idx):
def test_mul_index(self, numeric_idx):
# in general not true for RangeIndex
idx = numeric_idx
- if not isinstance(idx, pd.RangeIndex):
+ if not isinstance(idx, RangeIndex):
result = idx * idx
tm.assert_index_equal(result, idx ** 2)
@@ -680,7 +690,7 @@ def test_pow_float(self, op, numeric_idx, box_with_array):
# test power calculations both ways, GH#14973
box = box_with_array
idx = numeric_idx
- expected = pd.Float64Index(op(idx.values, 2.0))
+ expected = Float64Index(op(idx.values, 2.0))
idx = tm.box_expected(idx, box)
expected = tm.box_expected(expected, box)
@@ -1040,74 +1050,70 @@ def test_series_divmod_zero(self):
class TestUFuncCompat:
@pytest.mark.parametrize(
"holder",
- [pd.Int64Index, pd.UInt64Index, pd.Float64Index, pd.RangeIndex, Series],
+ [Int64Index, UInt64Index, Float64Index, RangeIndex, Series],
)
def test_ufunc_compat(self, holder):
box = Series if holder is Series else Index
- if holder is pd.RangeIndex:
- idx = pd.RangeIndex(0, 5)
+ if holder is RangeIndex:
+ idx = RangeIndex(0, 5)
else:
idx = holder(np.arange(5, dtype="int64"))
result = np.sin(idx)
expected = box(np.sin(np.arange(5, dtype="int64")))
tm.assert_equal(result, expected)
- @pytest.mark.parametrize(
- "holder", [pd.Int64Index, pd.UInt64Index, pd.Float64Index, Series]
- )
+ @pytest.mark.parametrize("holder", [Int64Index, UInt64Index, Float64Index, Series])
def test_ufunc_coercions(self, holder):
idx = holder([1, 2, 3, 4, 5], name="x")
box = Series if holder is Series else Index
result = np.sqrt(idx)
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index(np.sqrt(np.array([1, 2, 3, 4, 5])), name="x")
+ exp = Float64Index(np.sqrt(np.array([1, 2, 3, 4, 5])), name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
result = np.divide(idx, 2.0)
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index([0.5, 1.0, 1.5, 2.0, 2.5], name="x")
+ exp = Float64Index([0.5, 1.0, 1.5, 2.0, 2.5], name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
# _evaluate_numeric_binop
result = idx + 2.0
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index([3.0, 4.0, 5.0, 6.0, 7.0], name="x")
+ exp = Float64Index([3.0, 4.0, 5.0, 6.0, 7.0], name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
result = idx - 2.0
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index([-1.0, 0.0, 1.0, 2.0, 3.0], name="x")
+ exp = Float64Index([-1.0, 0.0, 1.0, 2.0, 3.0], name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
result = idx * 1.0
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index([1.0, 2.0, 3.0, 4.0, 5.0], name="x")
+ exp = Float64Index([1.0, 2.0, 3.0, 4.0, 5.0], name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
result = idx / 2.0
assert result.dtype == "f8" and isinstance(result, box)
- exp = pd.Float64Index([0.5, 1.0, 1.5, 2.0, 2.5], name="x")
+ exp = Float64Index([0.5, 1.0, 1.5, 2.0, 2.5], name="x")
exp = tm.box_expected(exp, box)
tm.assert_equal(result, exp)
- @pytest.mark.parametrize(
- "holder", [pd.Int64Index, pd.UInt64Index, pd.Float64Index, Series]
- )
+ @pytest.mark.parametrize("holder", [Int64Index, UInt64Index, Float64Index, Series])
def test_ufunc_multiple_return_values(self, holder):
obj = holder([1, 2, 3], name="x")
box = Series if holder is Series else Index
result = np.modf(obj)
assert isinstance(result, tuple)
- exp1 = pd.Float64Index([0.0, 0.0, 0.0], name="x")
- exp2 = pd.Float64Index([1.0, 2.0, 3.0], name="x")
+ exp1 = Float64Index([0.0, 0.0, 0.0], name="x")
+ exp2 = Float64Index([1.0, 2.0, 3.0], name="x")
tm.assert_equal(result[0], tm.box_expected(exp1, box))
tm.assert_equal(result[1], tm.box_expected(exp2, box))
@@ -1173,12 +1179,12 @@ def check_binop(self, ops, scalars, idxs):
for op in ops:
for a, b in combinations(idxs, 2):
result = op(a, b)
- expected = op(pd.Int64Index(a), pd.Int64Index(b))
+ expected = op(Int64Index(a), Int64Index(b))
tm.assert_index_equal(result, expected)
for idx in idxs:
for scalar in scalars:
result = op(idx, scalar)
- expected = op(pd.Int64Index(idx), scalar)
+ expected = op(Int64Index(idx), scalar)
tm.assert_index_equal(result, expected)
def test_binops(self):
@@ -1191,10 +1197,10 @@ def test_binops(self):
]
scalars = [-1, 1, 2]
idxs = [
- pd.RangeIndex(0, 10, 1),
- pd.RangeIndex(0, 20, 2),
- pd.RangeIndex(-10, 10, 2),
- pd.RangeIndex(5, -5, -1),
+ RangeIndex(0, 10, 1),
+ RangeIndex(0, 20, 2),
+ RangeIndex(-10, 10, 2),
+ RangeIndex(5, -5, -1),
]
self.check_binop(ops, scalars, idxs)
@@ -1203,7 +1209,7 @@ def test_binops_pow(self):
# https://github.com/numpy/numpy/pull/8127
ops = [pow]
scalars = [1, 2]
- idxs = [pd.RangeIndex(0, 10, 1), pd.RangeIndex(0, 20, 2)]
+ idxs = [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)]
self.check_binop(ops, scalars, idxs)
# TODO: mod, divmod?
@@ -1221,7 +1227,7 @@ def test_binops_pow(self):
def test_arithmetic_with_frame_or_series(self, op):
# check that we return NotImplemented when operating with Series
# or DataFrame
- index = pd.RangeIndex(5)
+ index = RangeIndex(5)
other = Series(np.random.randn(5))
expected = op(Series(index), other)
@@ -1237,26 +1243,26 @@ def test_numeric_compat2(self):
# validate that we are handling the RangeIndex overrides to numeric ops
# and returning RangeIndex where possible
- idx = pd.RangeIndex(0, 10, 2)
+ idx = RangeIndex(0, 10, 2)
result = idx * 2
- expected = pd.RangeIndex(0, 20, 4)
+ expected = RangeIndex(0, 20, 4)
tm.assert_index_equal(result, expected, exact=True)
result = idx + 2
- expected = pd.RangeIndex(2, 12, 2)
+ expected = RangeIndex(2, 12, 2)
tm.assert_index_equal(result, expected, exact=True)
result = idx - 2
- expected = pd.RangeIndex(-2, 8, 2)
+ expected = RangeIndex(-2, 8, 2)
tm.assert_index_equal(result, expected, exact=True)
result = idx / 2
- expected = pd.RangeIndex(0, 5, 1).astype("float64")
+ expected = RangeIndex(0, 5, 1).astype("float64")
tm.assert_index_equal(result, expected, exact=True)
result = idx / 4
- expected = pd.RangeIndex(0, 10, 2) / 4
+ expected = RangeIndex(0, 10, 2) / 4
tm.assert_index_equal(result, expected, exact=True)
result = idx // 1
@@ -1269,25 +1275,25 @@ def test_numeric_compat2(self):
tm.assert_index_equal(result, expected, exact=True)
# __pow__
- idx = pd.RangeIndex(0, 1000, 2)
+ idx = RangeIndex(0, 1000, 2)
result = idx ** 2
expected = idx._int64index ** 2
tm.assert_index_equal(Index(result.values), expected, exact=True)
# __floordiv__
cases_exact = [
- (pd.RangeIndex(0, 1000, 2), 2, pd.RangeIndex(0, 500, 1)),
- (pd.RangeIndex(-99, -201, -3), -3, pd.RangeIndex(33, 67, 1)),
- (pd.RangeIndex(0, 1000, 1), 2, pd.RangeIndex(0, 1000, 1)._int64index // 2),
+ (RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)),
+ (RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)),
+ (RangeIndex(0, 1000, 1), 2, RangeIndex(0, 1000, 1)._int64index // 2),
(
- pd.RangeIndex(0, 100, 1),
+ RangeIndex(0, 100, 1),
2.0,
- pd.RangeIndex(0, 100, 1)._int64index // 2.0,
+ RangeIndex(0, 100, 1)._int64index // 2.0,
),
- (pd.RangeIndex(0), 50, pd.RangeIndex(0)),
- (pd.RangeIndex(2, 4, 2), 3, pd.RangeIndex(0, 1, 1)),
- (pd.RangeIndex(-5, -10, -6), 4, pd.RangeIndex(-2, -1, 1)),
- (pd.RangeIndex(-100, -200, 3), 2, pd.RangeIndex(0)),
+ (RangeIndex(0), 50, RangeIndex(0)),
+ (RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)),
+ (RangeIndex(-5, -10, -6), 4, RangeIndex(-2, -1, 1)),
+ (RangeIndex(-100, -200, 3), 2, RangeIndex(0)),
]
for idx, div, expected in cases_exact:
tm.assert_index_equal(idx // div, expected, exact=True)
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 438a22c99a4eb..014094923185f 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -45,6 +45,7 @@
Index,
Interval,
Period,
+ PeriodIndex,
Series,
Timedelta,
TimedeltaIndex,
@@ -884,30 +885,30 @@ def test_infer_dtype_timedelta_with_na(self, na_value, delta):
def test_infer_dtype_period(self):
# GH 13664
- arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="D")])
+ arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="D")])
assert lib.infer_dtype(arr, skipna=True) == "period"
- arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="M")])
+ arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")])
assert lib.infer_dtype(arr, skipna=True) == "period"
def test_infer_dtype_period_mixed(self):
arr = np.array(
- [pd.Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object
+ [Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object
)
assert lib.infer_dtype(arr, skipna=False) == "mixed"
arr = np.array(
- [np.datetime64("nat"), pd.Period("2011-01", freq="M")], dtype=object
+ [np.datetime64("nat"), Period("2011-01", freq="M")], dtype=object
)
assert lib.infer_dtype(arr, skipna=False) == "mixed"
@pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
def test_infer_dtype_period_with_na(self, na_value):
# starts with nan
- arr = np.array([na_value, pd.Period("2011-01", freq="D")])
+ arr = np.array([na_value, Period("2011-01", freq="D")])
assert lib.infer_dtype(arr, skipna=True) == "period"
- arr = np.array([na_value, pd.Period("2011-01", freq="D"), na_value])
+ arr = np.array([na_value, Period("2011-01", freq="D"), na_value])
assert lib.infer_dtype(arr, skipna=True) == "period"
@pytest.mark.parametrize(
@@ -1192,8 +1193,8 @@ def test_to_object_array_width(self):
tm.assert_numpy_array_equal(out, expected)
def test_is_period(self):
- assert lib.is_period(pd.Period("2011-01", freq="M"))
- assert not lib.is_period(pd.PeriodIndex(["2011-01"], freq="M"))
+ assert lib.is_period(Period("2011-01", freq="M"))
+ assert not lib.is_period(PeriodIndex(["2011-01"], freq="M"))
assert not lib.is_period(Timestamp("2011-01"))
assert not lib.is_period(1)
assert not lib.is_period(np.nan)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index cd1fc67772849..da556523a3341 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -8,7 +8,16 @@
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv
+from pandas import (
+ DataFrame,
+ Grouper,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ read_csv,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
import pandas.core.common as com
@@ -16,7 +25,7 @@
def test_repr():
# GH18203
- result = repr(pd.Grouper(key="A", level="B"))
+ result = repr(Grouper(key="A", level="B"))
expected = "Grouper(key='A', level='B', axis=0, sort=False)"
assert result == expected
@@ -1218,7 +1227,7 @@ def test_groupby_keys_same_size_as_index():
start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq
)
df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index)
- result = df.groupby([pd.Grouper(level=0, freq=freq), "metric"]).mean()
+ result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean()
expected = df.set_index([df.index, "metric"])
tm.assert_frame_equal(result, expected)
@@ -1815,7 +1824,7 @@ def test_groupby_agg_ohlc_non_first():
index=pd.date_range("2018-01-01", periods=2, freq="D"),
)
- result = df.groupby(pd.Grouper(freq="D")).agg(["sum", "ohlc"])
+ result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"])
tm.assert_frame_equal(result, expected)
@@ -1866,11 +1875,11 @@ def test_groupby_groups_in_BaseGrouper():
# Test if DataFrame grouped with a pandas.Grouper has correct groups
mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"])
df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi)
- result = df.groupby([pd.Grouper(level="alpha"), "beta"])
+ result = df.groupby([Grouper(level="alpha"), "beta"])
expected = df.groupby(["alpha", "beta"])
assert result.groups == expected.groups
- result = df.groupby(["beta", pd.Grouper(level="alpha")])
+ result = df.groupby(["beta", Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups
diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py
index c3282758a23f2..2340168415382 100644
--- a/pandas/tests/groupby/test_timegrouper.py
+++ b/pandas/tests/groupby/test_timegrouper.py
@@ -61,10 +61,10 @@ def test_groupby_with_timegrouper(self):
tm.assert_frame_equal(result1, expected)
df_sorted = df.sort_index()
- result2 = df_sorted.groupby(pd.Grouper(freq="5D")).sum()
+ result2 = df_sorted.groupby(Grouper(freq="5D")).sum()
tm.assert_frame_equal(result2, expected)
- result3 = df.groupby(pd.Grouper(freq="5D")).sum()
+ result3 = df.groupby(Grouper(freq="5D")).sum()
tm.assert_frame_equal(result3, expected)
@pytest.mark.parametrize("should_sort", [True, False])
@@ -92,7 +92,7 @@ def test_groupby_with_timegrouper_methods(self, should_sort):
df = df.sort_values(by="Quantity", ascending=False)
df = df.set_index("Date", drop=False)
- g = df.groupby(pd.Grouper(freq="6M"))
+ g = df.groupby(Grouper(freq="6M"))
assert g.group_keys
assert isinstance(g.grouper, BinGrouper)
@@ -138,7 +138,7 @@ def test_timegrouper_with_reg_groups(self):
}
).set_index(["Date", "Buyer"])
- result = df.groupby([pd.Grouper(freq="A"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="A"), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
expected = DataFrame(
@@ -153,7 +153,7 @@ def test_timegrouper_with_reg_groups(self):
],
}
).set_index(["Date", "Buyer"])
- result = df.groupby([pd.Grouper(freq="6MS"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="6MS"), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
df_original = DataFrame(
@@ -191,10 +191,10 @@ def test_timegrouper_with_reg_groups(self):
}
).set_index(["Date", "Buyer"])
- result = df.groupby([pd.Grouper(freq="1D"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1D"), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
- result = df.groupby([pd.Grouper(freq="1M"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1M"), "Buyer"]).sum()
expected = DataFrame(
{
"Buyer": "Carl Joe Mark".split(),
@@ -210,26 +210,26 @@ def test_timegrouper_with_reg_groups(self):
# passing the name
df = df.reset_index()
- result = df.groupby([pd.Grouper(freq="1M", key="Date"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
with pytest.raises(KeyError, match="'The grouper name foo is not found'"):
- df.groupby([pd.Grouper(freq="1M", key="foo"), "Buyer"]).sum()
+ df.groupby([Grouper(freq="1M", key="foo"), "Buyer"]).sum()
# passing the level
df = df.set_index("Date")
- result = df.groupby([pd.Grouper(freq="1M", level="Date"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1M", level="Date"), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
- result = df.groupby([pd.Grouper(freq="1M", level=0), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1M", level=0), "Buyer"]).sum()
tm.assert_frame_equal(result, expected)
with pytest.raises(ValueError, match="The level foo is not valid"):
- df.groupby([pd.Grouper(freq="1M", level="foo"), "Buyer"]).sum()
+ df.groupby([Grouper(freq="1M", level="foo"), "Buyer"]).sum()
# multi names
df = df.copy()
df["Date"] = df.index + pd.offsets.MonthEnd(2)
- result = df.groupby([pd.Grouper(freq="1M", key="Date"), "Buyer"]).sum()
+ result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum()
expected = DataFrame(
{
"Buyer": "Carl Joe Mark".split(),
@@ -247,7 +247,7 @@ def test_timegrouper_with_reg_groups(self):
msg = "The Grouper cannot specify both a key and a level!"
with pytest.raises(ValueError, match=msg):
df.groupby(
- [pd.Grouper(freq="1M", key="Date", level="Date"), "Buyer"]
+ [Grouper(freq="1M", key="Date", level="Date"), "Buyer"]
).sum()
# single groupers
@@ -258,18 +258,18 @@ def test_timegrouper_with_reg_groups(self):
[datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date"
),
)
- result = df.groupby(pd.Grouper(freq="1M")).sum()
+ result = df.groupby(Grouper(freq="1M")).sum()
tm.assert_frame_equal(result, expected)
- result = df.groupby([pd.Grouper(freq="1M")]).sum()
+ result = df.groupby([Grouper(freq="1M")]).sum()
tm.assert_frame_equal(result, expected)
expected.index = expected.index.shift(1)
assert expected.index.freq == offsets.MonthEnd()
- result = df.groupby(pd.Grouper(freq="1M", key="Date")).sum()
+ result = df.groupby(Grouper(freq="1M", key="Date")).sum()
tm.assert_frame_equal(result, expected)
- result = df.groupby([pd.Grouper(freq="1M", key="Date")]).sum()
+ result = df.groupby([Grouper(freq="1M", key="Date")]).sum()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("freq", ["D", "M", "A", "Q-APR"])
@@ -324,13 +324,11 @@ def test_timegrouper_with_reg_groups_freq(self, freq):
expected.name = "whole_cost"
result1 = (
- df.sort_index()
- .groupby([pd.Grouper(freq=freq), "user_id"])["whole_cost"]
- .sum()
+ df.sort_index().groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
)
tm.assert_series_equal(result1, expected)
- result2 = df.groupby([pd.Grouper(freq=freq), "user_id"])["whole_cost"].sum()
+ result2 = df.groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
tm.assert_series_equal(result2, expected)
def test_timegrouper_get_group(self):
@@ -361,7 +359,7 @@ def test_timegrouper_get_group(self):
dt_list = ["2013-09-30", "2013-10-31", "2013-12-31"]
for df in [df_original, df_reordered]:
- grouped = df.groupby(pd.Grouper(freq="M", key="Date"))
+ grouped = df.groupby(Grouper(freq="M", key="Date"))
for t, expected in zip(dt_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group(dt)
@@ -376,7 +374,7 @@ def test_timegrouper_get_group(self):
g_list = [("Joe", "2013-09-30"), ("Carl", "2013-10-31"), ("Joe", "2013-12-31")]
for df in [df_original, df_reordered]:
- grouped = df.groupby(["Buyer", pd.Grouper(freq="M", key="Date")])
+ grouped = df.groupby(["Buyer", Grouper(freq="M", key="Date")])
for (b, t), expected in zip(g_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group((b, dt))
@@ -393,7 +391,7 @@ def test_timegrouper_get_group(self):
]
for df in [df_original, df_reordered]:
- grouped = df.groupby(pd.Grouper(freq="M"))
+ grouped = df.groupby(Grouper(freq="M"))
for t, expected in zip(dt_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group(dt)
@@ -410,8 +408,8 @@ def test_timegrouper_apply_return_type_series(self):
def sumfunc_series(x):
return Series([x["value"].sum()], ("sum",))
- expected = df.groupby(pd.Grouper(key="date")).apply(sumfunc_series)
- result = df_dt.groupby(pd.Grouper(freq="M", key="date")).apply(sumfunc_series)
+ expected = df.groupby(Grouper(key="date")).apply(sumfunc_series)
+ result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_series)
tm.assert_frame_equal(
result.reset_index(drop=True), expected.reset_index(drop=True)
)
@@ -427,7 +425,7 @@ def test_timegrouper_apply_return_type_value(self):
def sumfunc_value(x):
return x.value.sum()
- expected = df.groupby(pd.Grouper(key="date")).apply(sumfunc_value)
+ expected = df.groupby(Grouper(key="date")).apply(sumfunc_value)
result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_value)
tm.assert_series_equal(
result.reset_index(drop=True), expected.reset_index(drop=True)
@@ -744,7 +742,7 @@ def test_nunique_with_timegrouper_and_nat(self):
}
)
- grouper = pd.Grouper(key="time", freq="h")
+ grouper = Grouper(key="time", freq="h")
result = test.groupby(grouper)["data"].nunique()
expected = test[test.time.notnull()].groupby(grouper)["data"].nunique()
expected.index = expected.index._with_freq(None)
@@ -761,7 +759,7 @@ def test_scalar_call_versus_list_call(self):
"value": [1, 2, 3],
}
data_frame = DataFrame(data_frame).set_index("time")
- grouper = pd.Grouper(freq="D")
+ grouper = Grouper(freq="D")
grouped = data_frame.groupby(grouper)
result = grouped.count()
diff --git a/pandas/tests/indexes/categorical/test_map.py b/pandas/tests/indexes/categorical/test_map.py
index 1a326c1acea46..c15818bc87f7c 100644
--- a/pandas/tests/indexes/categorical/test_map.py
+++ b/pandas/tests/indexes/categorical/test_map.py
@@ -25,16 +25,16 @@ def test_map_str(self, data, categories, ordered):
tm.assert_index_equal(result, expected)
def test_map(self):
- ci = pd.CategoricalIndex(list("ABABC"), categories=list("CBA"), ordered=True)
+ ci = CategoricalIndex(list("ABABC"), categories=list("CBA"), ordered=True)
result = ci.map(lambda x: x.lower())
- exp = pd.CategoricalIndex(list("ababc"), categories=list("cba"), ordered=True)
+ exp = CategoricalIndex(list("ababc"), categories=list("cba"), ordered=True)
tm.assert_index_equal(result, exp)
- ci = pd.CategoricalIndex(
+ ci = CategoricalIndex(
list("ABABC"), categories=list("BAC"), ordered=False, name="XXX"
)
result = ci.map(lambda x: x.lower())
- exp = pd.CategoricalIndex(
+ exp = CategoricalIndex(
list("ababc"), categories=list("bac"), ordered=False, name="XXX"
)
tm.assert_index_equal(result, exp)
@@ -45,13 +45,13 @@ def test_map(self):
)
# change categories dtype
- ci = pd.CategoricalIndex(list("ABABC"), categories=list("BAC"), ordered=False)
+ ci = CategoricalIndex(list("ABABC"), categories=list("BAC"), ordered=False)
def f(x):
return {"A": 10, "B": 20, "C": 30}.get(x)
result = ci.map(f)
- exp = pd.CategoricalIndex(
+ exp = CategoricalIndex(
[10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False
)
tm.assert_index_equal(result, exp)
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 45683ba48b4c4..ff871ee45daed 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -869,7 +869,7 @@ def test_set_closed_errors(self, bad_closed):
def test_is_all_dates(self):
# GH 23576
- year_2017 = pd.Interval(
+ year_2017 = Interval(
Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")
)
year_2017_index = pd.IntervalIndex([year_2017])
diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py
index 10134b20e7d3e..8e7cb7d86edf5 100644
--- a/pandas/tests/indexes/period/test_ops.py
+++ b/pandas/tests/indexes/period/test_ops.py
@@ -270,17 +270,17 @@ def test_order(self):
assert ordered.freq == "D"
def test_nat(self):
- assert pd.PeriodIndex._na_value is NaT
- assert pd.PeriodIndex([], freq="M")._na_value is NaT
+ assert PeriodIndex._na_value is NaT
+ assert PeriodIndex([], freq="M")._na_value is NaT
- idx = pd.PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")
+ idx = PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")
assert idx._can_hold_na
tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
assert idx.hasnans is False
tm.assert_numpy_array_equal(idx._nan_idxs, np.array([], dtype=np.intp))
- idx = pd.PeriodIndex(["2011-01-01", "NaT"], freq="D")
+ idx = PeriodIndex(["2011-01-01", "NaT"], freq="D")
assert idx._can_hold_na
tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
@@ -290,7 +290,7 @@ def test_nat(self):
@pytest.mark.parametrize("freq", ["D", "M"])
def test_equals(self, freq):
# GH#13107
- idx = pd.PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq)
+ idx = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq)
assert idx.equals(idx)
assert idx.equals(idx.copy())
assert idx.equals(idx.astype(object))
@@ -299,7 +299,7 @@ def test_equals(self, freq):
assert not idx.equals(list(idx))
assert not idx.equals(Series(idx))
- idx2 = pd.PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="H")
+ idx2 = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="H")
assert not idx.equals(idx2)
assert not idx.equals(idx2.copy())
assert not idx.equals(idx2.astype(object))
@@ -308,7 +308,7 @@ def test_equals(self, freq):
assert not idx.equals(Series(idx2))
# same internal, different tz
- idx3 = pd.PeriodIndex._simple_new(
+ idx3 = PeriodIndex._simple_new(
idx._values._simple_new(idx._values.asi8, freq="H")
)
tm.assert_numpy_array_equal(idx.asi8, idx3.asi8)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index c8fbbcf9aed20..1d75ed25ad2e9 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -27,6 +27,7 @@
MultiIndex,
NaT,
Period,
+ RangeIndex,
Series,
Timestamp,
date_range,
@@ -267,7 +268,7 @@ def test_constructor_index_dtype(self, dtype):
(["1", "2"]),
(list(pd.date_range("1/1/2011", periods=2, freq="H"))),
(list(pd.date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
- ([pd.Interval(left=0, right=5)]),
+ ([Interval(left=0, right=5)]),
],
)
def test_constructor_list_str(self, input_vals, string_dtype):
@@ -624,7 +625,7 @@ def test_constructor_copy(self):
pd.period_range("2012Q1", periods=3, freq="Q"),
Index(list("abc")),
pd.Int64Index([1, 2, 3]),
- pd.RangeIndex(0, 3),
+ RangeIndex(0, 3),
],
ids=lambda x: type(x).__name__,
)
@@ -1004,7 +1005,7 @@ def test_construction_interval(self, interval_constructor):
)
def test_constructor_infer_interval(self, data_constructor):
# GH 23563: consistent closed results in interval dtype
- data = [pd.Interval(0, 1), pd.Interval(0, 2), None]
+ data = [Interval(0, 1), Interval(0, 2), None]
result = Series(data_constructor(data))
expected = Series(IntervalArray(data))
assert result.dtype == "interval[float64]"
@@ -1015,7 +1016,7 @@ def test_constructor_infer_interval(self, data_constructor):
)
def test_constructor_interval_mixed_closed(self, data_constructor):
# GH 23563: mixed closed results in object dtype (not interval dtype)
- data = [pd.Interval(0, 1, closed="both"), pd.Interval(0, 2, closed="neither")]
+ data = [Interval(0, 1, closed="both"), Interval(0, 2, closed="neither")]
result = Series(data_constructor(data))
assert result.dtype == object
assert result.tolist() == data
| - [x] closes #37838
- [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/37852 | 2020-11-14T19:56:38Z | 2020-11-16T04:48:03Z | 2020-11-16T04:48:03Z | 2020-11-16T10:00:16Z |
CLN: remove no-longer-used ignore_failures in frame_apply | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index fa4fbe711fbe4..c5260deafc0c3 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -26,7 +26,6 @@ def frame_apply(
axis: Axis = 0,
raw: bool = False,
result_type: Optional[str] = None,
- ignore_failures: bool = False,
args=None,
kwds=None,
):
@@ -43,7 +42,6 @@ def frame_apply(
func,
raw=raw,
result_type=result_type,
- ignore_failures=ignore_failures,
args=args,
kwds=kwds,
)
@@ -84,13 +82,11 @@ def __init__(
func,
raw: bool,
result_type: Optional[str],
- ignore_failures: bool,
args,
kwds,
):
self.obj = obj
self.raw = raw
- self.ignore_failures = ignore_failures
self.args = args or ()
self.kwds = kwds or {}
@@ -283,29 +279,14 @@ def apply_series_generator(self) -> Tuple[ResType, "Index"]:
results = {}
- if self.ignore_failures:
- successes = []
+ with option_context("mode.chained_assignment", None):
for i, v in enumerate(series_gen):
- try:
- results[i] = self.f(v)
- except Exception:
- pass
- else:
- successes.append(i)
-
- # so will work with MultiIndex
- if len(successes) < len(res_index):
- res_index = res_index.take(successes)
-
- else:
- with option_context("mode.chained_assignment", None):
- for i, v in enumerate(series_gen):
- # ignore SettingWithCopy here in case the user mutates
- results[i] = self.f(v)
- if isinstance(results[i], ABCSeries):
- # If we have a view on v, we need to make a copy because
- # series_generator will swap out the underlying data
- results[i] = results[i].copy(deep=False)
+ # ignore SettingWithCopy here in case the user mutates
+ results[i] = self.f(v)
+ if isinstance(results[i], ABCSeries):
+ # If we have a view on v, we need to make a copy because
+ # series_generator will swap out the underlying data
+ results[i] = results[i].copy(deep=False)
return results, res_index
diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py
index 162035b53d68d..f080d4b8bcc36 100644
--- a/pandas/tests/frame/apply/test_frame_apply.py
+++ b/pandas/tests/frame/apply/test_frame_apply.py
@@ -10,7 +10,6 @@
import pandas as pd
from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, notna
import pandas._testing as tm
-from pandas.core.apply import frame_apply
from pandas.core.base import SpecificationError
from pandas.tests.frame.common import zip_frames
@@ -267,13 +266,6 @@ def test_apply_axis1(self, float_frame):
tapplied = float_frame.apply(np.mean, axis=1)
assert tapplied[d] == np.mean(float_frame.xs(d))
- def test_apply_ignore_failures(self, float_string_frame):
- result = frame_apply(
- float_string_frame, np.mean, 0, ignore_failures=True
- ).apply_standard()
- expected = float_string_frame._get_numeric_data().apply(np.mean)
- tm.assert_series_equal(result, expected)
-
def test_apply_mixed_dtype_corner(self):
df = DataFrame({"A": ["foo"], "B": [1.0]})
result = df[:0].apply(np.mean, axis=1)
| https://api.github.com/repos/pandas-dev/pandas/pulls/37851 | 2020-11-14T19:54:49Z | 2020-11-15T17:30:16Z | 2020-11-15T17:30:16Z | 2020-11-15T18:14:33Z | |
Backport PR #37787 on branch 1.1.x (Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex) | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index 2a598c489e809..323342cb43950 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
+- Fixed regression in :meth:`DataFrame.loc` and :meth:`Series.loc` for ``__setitem__`` when one-dimensional tuple was given to select from :class:`MultiIndex` (:issue:`37711`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index d21ff6ee17537..c33cb396e576b 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -641,9 +641,9 @@ def _ensure_listlike_indexer(self, key, axis=None):
if self.ndim != 2:
return
- if isinstance(key, tuple):
+ if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex):
# key may be a tuple if we are .loc
- # in that case, set key to the column part of key
+ # if index is not a MultiIndex, set key to column part
key = key[column_axis]
axis = column_axis
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 95a23a9bcf63b..4ee7e34bc4a0c 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -288,6 +288,24 @@ def convert_nested_indexer(indexer_type, keys):
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("klass", [Series, DataFrame])
+ def test_multiindex_loc_one_dimensional_tuple(self, klass):
+ # GH#37711
+ mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
+ obj = klass([1, 2], index=mi)
+ obj.loc[("a",)] = 0
+ expected = klass([0, 2], index=mi)
+ tm.assert_equal(obj, expected)
+
+ @pytest.mark.parametrize("indexer", [("a",), ("a")])
+ def test_multiindex_one_dimensional_tuple_columns(self, indexer):
+ # GH#37711
+ mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
+ obj = DataFrame([1, 2], index=mi)
+ obj.loc[indexer, :] = 0
+ expected = DataFrame([0, 2], index=mi)
+ tm.assert_frame_equal(obj, expected)
+
@pytest.mark.parametrize(
"indexer, pos",
| Backport #37787
``frame_or_series`` not know here.
cc @simonjayhawkins | https://api.github.com/repos/pandas-dev/pandas/pulls/37849 | 2020-11-14T19:48:25Z | 2020-11-15T10:31:49Z | 2020-11-15T10:31:49Z | 2020-11-15T11:16:31Z |
Updated script to check inconsistent pandas namespace | diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index e81b919dbad2d..149389b936def 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -81,7 +81,7 @@ def zero(request):
Examples
--------
- >>> arr = pd.RangeIndex(5)
+ >>> arr = RangeIndex(5)
>>> arr / zeros
Float64Index([nan, inf, inf, inf, inf], dtype='float64')
"""
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 31c7a17fd9ef5..0202337a4389a 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -465,7 +465,7 @@ def test_addition_ops(self):
tdi + pd.Int64Index([1, 2, 3])
# this is a union!
- # pytest.raises(TypeError, lambda : Int64Index([1,2,3]) + tdi)
+ # pytest.raises(TypeError, lambda : pd.Int64Index([1,2,3]) + tdi)
result = tdi + dti # name will be reset
expected = DatetimeIndex(["20130102", pd.NaT, "20130105"])
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 23921356a2c5d..dab7fc51f2537 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -677,7 +677,7 @@ def test_interval(self):
tm.assert_index_equal(cat.categories, idx)
# overlapping
- idx = pd.IntervalIndex([pd.Interval(0, 2), pd.Interval(0, 1)])
+ idx = IntervalIndex([Interval(0, 2), Interval(0, 1)])
cat = Categorical(idx, categories=idx)
expected_codes = np.array([0, 1], dtype="int8")
tm.assert_numpy_array_equal(cat.codes, expected_codes)
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index f53378d86d7c6..951a462bad3e3 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -720,8 +720,8 @@ def test_constructor_period_dict(self):
@pytest.mark.parametrize(
"data,dtype",
[
- (pd.Period("2012-01", freq="M"), "period[M]"),
- (pd.Period("2012-02-01", freq="D"), "period[D]"),
+ (Period("2012-01", freq="M"), "period[M]"),
+ (Period("2012-02-01", freq="D"), "period[D]"),
(Interval(left=0, right=5), IntervalDtype("int64")),
(Interval(left=0.1, right=0.5), IntervalDtype("float64")),
],
@@ -2577,7 +2577,7 @@ def test_from_records_series_list_dict(self):
def test_from_records_series_categorical_index(self):
# GH 32805
index = CategoricalIndex(
- [pd.Interval(-20, -10), pd.Interval(-10, 0), pd.Interval(0, 10)]
+ [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)]
)
series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index)
frame = DataFrame.from_records(series_of_dicts, index=index)
@@ -2628,7 +2628,7 @@ class List(list):
[
Categorical(list("aabbc")),
SparseArray([1, np.nan, np.nan, np.nan]),
- IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]),
+ IntervalArray([Interval(0, 1), Interval(1, 5)]),
PeriodArray(pd.period_range(start="1/1/2017", end="1/1/2018", freq="M")),
],
)
@@ -2648,12 +2648,10 @@ def test_datetime_date_tuple_columns_from_dict(self):
def test_construct_with_two_categoricalindex_series(self):
# GH 14600
- s1 = Series(
- [39, 6, 4], index=pd.CategoricalIndex(["female", "male", "unknown"])
- )
+ s1 = Series([39, 6, 4], index=CategoricalIndex(["female", "male", "unknown"]))
s2 = Series(
[2, 152, 2, 242, 150],
- index=pd.CategoricalIndex(["f", "female", "m", "male", "unknown"]),
+ index=CategoricalIndex(["f", "female", "m", "male", "unknown"]),
)
result = DataFrame([s1, s2])
expected = DataFrame(
@@ -2717,7 +2715,7 @@ def test_dataframe_constructor_infer_multiindex(self):
(["1", "2"]),
(list(date_range("1/1/2011", periods=2, freq="H"))),
(list(date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
- ([pd.Interval(left=0, right=5)]),
+ ([Interval(left=0, right=5)]),
],
)
def test_constructor_list_str(self, input_vals, string_dtype):
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index ff871ee45daed..fffaf3830560f 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -228,7 +228,7 @@ def test_is_unique_interval(self, closed):
assert idx.is_unique is True
# unique overlapping - shared endpoints
- idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
assert idx.is_unique is True
# unique nested
@@ -279,14 +279,14 @@ def test_monotonic(self, closed):
assert idx._is_strictly_monotonic_decreasing is False
# increasing overlapping shared endpoints
- idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
assert idx.is_monotonic is True
assert idx._is_strictly_monotonic_increasing is True
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# decreasing overlapping shared endpoints
- idx = pd.IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
+ idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
assert idx.is_monotonic is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is True
@@ -872,7 +872,7 @@ def test_is_all_dates(self):
year_2017 = Interval(
Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")
)
- year_2017_index = pd.IntervalIndex([year_2017])
+ year_2017_index = IntervalIndex([year_2017])
assert not year_2017_index._is_all_dates
@pytest.mark.parametrize("key", [[5], (2, 3)])
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index 76f2738948872..d69cbeac31a32 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -522,7 +522,7 @@ def test_constructor_coercion_signed_to_unsigned(self, uint_dtype):
def test_constructor_unwraps_index(self):
idx = Index([1, 2])
- result = pd.Int64Index(idx)
+ result = Int64Index(idx)
expected = np.array([1, 2], dtype="int64")
tm.assert_numpy_array_equal(result._data, expected)
@@ -614,8 +614,8 @@ def test_int_float_union_dtype(dtype):
# https://github.com/pandas-dev/pandas/issues/26778
# [u]int | float -> float
index = Index([0, 2, 3], dtype=dtype)
- other = pd.Float64Index([0.5, 1.5])
- expected = pd.Float64Index([0.0, 0.5, 1.5, 2.0, 3.0])
+ other = Float64Index([0.5, 1.5])
+ expected = Float64Index([0.0, 0.5, 1.5, 2.0, 3.0])
result = index.union(other)
tm.assert_index_equal(result, expected)
@@ -626,9 +626,9 @@ def test_int_float_union_dtype(dtype):
def test_range_float_union_dtype():
# https://github.com/pandas-dev/pandas/issues/26778
index = pd.RangeIndex(start=0, stop=3)
- other = pd.Float64Index([0.5, 1.5])
+ other = Float64Index([0.5, 1.5])
result = index.union(other)
- expected = pd.Float64Index([0.0, 0.5, 1, 1.5, 2.0])
+ expected = Float64Index([0.0, 0.5, 1, 1.5, 2.0])
tm.assert_index_equal(result, expected)
result = other.union(index)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 1d75ed25ad2e9..debd516da9eec 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1040,7 +1040,7 @@ def test_construction_consistency(self):
"data_constructor", [list, np.array], ids=["list", "ndarray[object]"]
)
def test_constructor_infer_period(self, data_constructor):
- data = [pd.Period("2000", "D"), pd.Period("2001", "D"), None]
+ data = [Period("2000", "D"), Period("2001", "D"), None]
result = Series(data_constructor(data))
expected = Series(period_array(data))
tm.assert_series_equal(result, expected)
@@ -1057,7 +1057,7 @@ def test_construct_from_ints_including_iNaT_scalar_period_dtype(self):
assert isna(series[2])
def test_constructor_period_incompatible_frequency(self):
- data = [pd.Period("2000", "D"), pd.Period("2001", "A")]
+ data = [Period("2000", "D"), Period("2001", "A")]
result = Series(data)
assert result.dtype == object
assert result.tolist() == data
@@ -1539,7 +1539,7 @@ def test_constructor_list_of_periods_infers_period_dtype(self):
assert series.dtype == "Period[D]"
series = Series(
- [pd.Period("2011-01-01", freq="D"), pd.Period("2011-02-01", freq="D")]
+ [Period("2011-01-01", freq="D"), Period("2011-02-01", freq="D")]
)
assert series.dtype == "Period[D]"
diff --git a/scripts/check_for_inconsistent_pandas_namespace.py b/scripts/check_for_inconsistent_pandas_namespace.py
index 4b4515cdf7e11..b213d931e7f07 100644
--- a/scripts/check_for_inconsistent_pandas_namespace.py
+++ b/scripts/check_for_inconsistent_pandas_namespace.py
@@ -16,29 +16,18 @@
PATTERN = r"""
(
- (?<!pd\.)(?<!\w) # check class_name start with pd. or character
- {class_name}\( # match DataFrame but not pd.DataFrame or tm.makeDataFrame
+ (?<!pd\.)(?<!\w) # check class_name doesn't start with pd. or character
+ ([A-Z]\w+)\( # match DataFrame but not pd.DataFrame or tm.makeDataFrame
.* # match anything
- pd\.{class_name}\( # only match e.g. pd.DataFrame
+ pd\.\2\( # only match e.g. pd.DataFrame
)|
(
- pd\.{class_name}\( # only match e.g. pd.DataFrame
+ pd\.([A-Z]\w+)\( # only match e.g. pd.DataFrame
.* # match anything
- (?<!pd\.)(?<!\w) # check class_name start with pd. or character
- {class_name}\( # match DataFrame but not pd.DataFrame or tm.makeDataFrame
+ (?<!pd\.)(?<!\w) # check class_name doesn't start with pd. or character
+ \4\( # match DataFrame but not pd.DataFrame or tm.makeDataFrame
)
"""
-CLASS_NAMES = (
- "Series",
- "DataFrame",
- "Index",
- "MultiIndex",
- "Timestamp",
- "Timedelta",
- "TimedeltaIndex",
- "DatetimeIndex",
- "Categorical",
-)
ERROR_MESSAGE = "Found both `pd.{class_name}` and `{class_name}` in {path}"
@@ -47,16 +36,22 @@ def main(argv: Optional[Sequence[str]] = None) -> None:
parser.add_argument("paths", nargs="*", type=Path)
args = parser.parse_args(argv)
- for class_name in CLASS_NAMES:
- pattern = re.compile(
- PATTERN.format(class_name=class_name).encode(),
- flags=re.MULTILINE | re.DOTALL | re.VERBOSE,
- )
- for path in args.paths:
- contents = path.read_bytes()
- match = pattern.search(contents)
- assert match is None, ERROR_MESSAGE.format(
- class_name=class_name, path=str(path)
+ pattern = re.compile(
+ PATTERN.encode(),
+ flags=re.MULTILINE | re.DOTALL | re.VERBOSE,
+ )
+ for path in args.paths:
+ contents = path.read_bytes()
+ match = pattern.search(contents)
+ if match is None:
+ continue
+ if match.group(2) is not None:
+ raise AssertionError(
+ ERROR_MESSAGE.format(class_name=match.group(2).decode(), path=str(path))
+ )
+ if match.group(4) is not None:
+ raise AssertionError(
+ ERROR_MESSAGE.format(class_name=match.group(4).decode(), path=str(path))
)
| - [ ] closes #37838
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Updates the script for inconsistent namespace usage. To be merged after all the errors are fixed with the updated script. The script is described here : https://github.com/MarcoGorelli/PyDataGlobal2020-sprint/issues/1 by @MarcoGorelli | https://api.github.com/repos/pandas-dev/pandas/pulls/37848 | 2020-11-14T19:43:11Z | 2020-11-18T19:04:37Z | 2020-11-18T19:04:37Z | 2020-11-18T19:04:43Z |
DOC: add unqiue value counts example to groupyby guide | diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst
index e19dace572e59..d6081155b58db 100644
--- a/doc/source/user_guide/groupby.rst
+++ b/doc/source/user_guide/groupby.rst
@@ -524,6 +524,15 @@ index are the group names and whose values are the sizes of each group.
grouped.describe()
+Another aggregation example is to compute the number of unique values of each group. This is similar to the ``value_counts`` function, except that it only counts unique values.
+
+.. ipython:: python
+
+ ll = [['foo', 1], ['foo', 2], ['foo', 2], ['bar', 1], ['bar', 1]]
+ df4 = pd.DataFrame(ll, columns=["A", "B"])
+ df4
+ df4.groupby("A")["B"].nunique()
+
.. note::
Aggregation functions **will not** return the groups that you are aggregating over
| Co-authored-by: Abdulelah Almesfer <28743265+abdulelahsm@users.noreply.github.com>
Co-authoerd-by: Abdulellah Alnumay <33042538+Abo7atm@users.noreply.github.com>
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Adding an example to the groupby user guide. The example showcases the usage of ```nunique``` aggregate function. This is from the PyData Global sprint, from [this issue](https://github.com/MarcoGorelli/PyDataGlobal2020-sprint/issues/5). The example is taken from [StackOverflow](https://stackoverflow.com/questions/15411158/pandas-countdistinct-equivalent). | https://api.github.com/repos/pandas-dev/pandas/pulls/37847 | 2020-11-14T19:28:09Z | 2020-11-25T13:30:36Z | 2020-11-25T13:30:36Z | 2020-11-25T13:30:39Z |
Added docs to fix GL08 errors in CustomBusinessHours | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index dbd094905cf24..1339dee954603 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1403,6 +1403,19 @@ cdef class BusinessDay(BusinessMixin):
cdef class BusinessHour(BusinessMixin):
"""
DateOffset subclass representing possibly n business hours.
+
+ Parameters
+ ----------
+ n : int, default 1
+ The number of months represented.
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
+ weekmask : str, Default 'Mon Tue Wed Thu Fri'
+ Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
+ start : str, default "09:00"
+ Start time of your custom business hour in 24h format.
+ end : str, default: "17:00"
+ End time of your custom business hour in 24h format.
"""
_prefix = "BH"
@@ -3251,6 +3264,19 @@ cdef class CustomBusinessDay(BusinessDay):
cdef class CustomBusinessHour(BusinessHour):
"""
DateOffset subclass representing possibly n custom business days.
+
+ Parameters
+ ----------
+ n : int, default 1
+ The number of months represented.
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
+ weekmask : str, Default 'Mon Tue Wed Thu Fri'
+ Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
+ start : str, default "09:00"
+ Start time of your custom business hour in 24h format.
+ end : str, default: "17:00"
+ End time of your custom business hour in 24h format.
"""
_prefix = "CBH"
| - [ ] xref #27977
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Currently even after adding the docstrings the command `python scripts/validate_docstrings.py --errors=GL08` does not pick up the changes. | https://api.github.com/repos/pandas-dev/pandas/pulls/37846 | 2020-11-14T19:18:58Z | 2020-11-17T01:32:30Z | 2020-11-17T01:32:30Z | 2020-11-17T01:32:36Z |
DOC: SS01 docstrings errors fixed | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index b5a6e32caa8e0..3eeee61f62a7e 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -225,7 +225,7 @@ fi
### DOCSTRINGS ###
if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
- MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS02, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA02, SA03)' ; echo $MSG
+ MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS01, SS02, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA02, SA03)' ; echo $MSG
$BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS02,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA02,SA03
RET=$(($RET + $?)) ; echo $MSG "DONE"
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 0b0334d52c1e9..f6d2d6e63340f 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -118,6 +118,8 @@ def memory_usage_of_objects(arr: object[:]) -> int64_t:
def is_scalar(val: object) -> bool:
"""
+ Return True if given object is scalar.
+
Parameters
----------
val : object
@@ -927,6 +929,8 @@ def indices_fast(ndarray index, const int64_t[:] labels, list keys,
def is_float(obj: object) -> bool:
"""
+ Return True if given object is float.
+
Returns
-------
bool
@@ -936,6 +940,8 @@ def is_float(obj: object) -> bool:
def is_integer(obj: object) -> bool:
"""
+ Return True if given object is integer.
+
Returns
-------
bool
@@ -945,6 +951,8 @@ def is_integer(obj: object) -> bool:
def is_bool(obj: object) -> bool:
"""
+ Return True if given object is boolean.
+
Returns
-------
bool
@@ -954,6 +962,8 @@ def is_bool(obj: object) -> bool:
def is_complex(obj: object) -> bool:
"""
+ Return True if given object is complex.
+
Returns
-------
bool
@@ -971,7 +981,7 @@ cpdef bint is_interval(object obj):
def is_period(val: object) -> bool:
"""
- Return a boolean if this is a Period object.
+ Return True if given object is Period.
Returns
-------
| xref #27977
- [ ] closes part of [MarcoGorelli/PyDataGlobal2020-sprint#4](https://github.com/MarcoGorelli/PyDataGlobal2020-sprint/issues/4)
- [ ] 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/37845 | 2020-11-14T19:16:28Z | 2020-11-15T09:02:54Z | 2020-11-15T09:02:54Z | 2020-11-15T20:55:14Z |
DOC: add examples to docstrings of assert_ functions | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 5dcd1247e52ba..87e99e520ab60 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -739,6 +739,13 @@ def assert_index_equal(
obj : str, default 'Index'
Specify object name being compared, internally used to show appropriate
assertion message.
+
+ Examples
+ --------
+ >>> from pandas.testing import assert_index_equal
+ >>> a = pd.Index([1, 2, 3])
+ >>> b = pd.Index([1, 2, 3])
+ >>> assert_index_equal(a, b)
"""
__tracebackhide__ = True
@@ -1205,6 +1212,13 @@ def assert_extension_array_equal(
Missing values are checked separately from valid values.
A mask of missing values is computed for each and checked to match.
The remaining all-valid values are cast to object dtype and checked.
+
+ Examples
+ --------
+ >>> from pandas.testing import assert_extension_array_equal
+ >>> a = pd.Series([1, 2, 3, 4])
+ >>> b, c = a.array, a.array
+ >>> assert_extension_array_equal(b, c)
"""
if check_less_precise is not no_default:
warnings.warn(
@@ -1334,6 +1348,13 @@ def assert_series_equal(
obj : str, default 'Series'
Specify object name being compared, internally used to show appropriate
assertion message.
+
+ Examples
+ --------
+ >>> from pandas.testing import assert_series_equal
+ >>> a = pd.Series([1, 2, 3, 4])
+ >>> b = pd.Series([1, 2, 3, 4])
+ >>> assert_series_equal(a, b)
"""
__tracebackhide__ = True
diff --git a/scripts/path_to_file.zip b/scripts/path_to_file.zip
new file mode 100644
index 0000000000000..ae2957e99dfae
Binary files /dev/null and b/scripts/path_to_file.zip differ
| - [ ] 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/37844 | 2020-11-14T19:05:17Z | 2020-11-16T20:39:16Z | 2020-11-16T20:39:16Z | 2020-11-16T20:39:36Z |
namespace consistency for test_dtype.py | diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py
index 30a23d8563ef8..6dc3b3b13dd0c 100644
--- a/pandas/tests/arithmetic/test_interval.py
+++ b/pandas/tests/arithmetic/test_interval.py
@@ -290,6 +290,6 @@ def test_index_series_compat(self, op, constructor, expected_type, assert_func):
def test_comparison_operations(self, scalars):
# GH #28981
expected = Series([False, False])
- s = Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype="interval")
+ s = Series([Interval(0, 1), Interval(1, 2)], dtype="interval")
result = s == scalars
tm.assert_series_equal(result, expected)
| - [x ] references #37838
- [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/37843 | 2020-11-14T19:01:18Z | 2020-11-15T09:03:51Z | 2020-11-15T09:03:51Z | 2020-11-15T09:03:51Z |
Fix cases of inconsistent namespacing in tests | diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index f9fcee889ec96..690d10054f4c4 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -125,7 +125,7 @@ def test_compare_object_dtype(self, box_with_array, other_box):
class TestPeriodIndexComparisons:
# TODO: parameterize over boxes
- @pytest.mark.parametrize("other", ["2017", pd.Period("2017", freq="D")])
+ @pytest.mark.parametrize("other", ["2017", Period("2017", freq="D")])
def test_eq(self, other):
idx = PeriodIndex(["2017", "2017", "2018"], freq="D")
expected = np.array([True, True, False])
@@ -362,10 +362,8 @@ def test_pi_cmp_nat_mismatched_freq_raises(self, freq):
# TODO: De-duplicate with test_pi_cmp_nat
@pytest.mark.parametrize("dtype", [object, None])
def test_comp_nat(self, dtype):
- left = pd.PeriodIndex(
- [pd.Period("2011-01-01"), pd.NaT, pd.Period("2011-01-03")]
- )
- right = pd.PeriodIndex([pd.NaT, pd.NaT, pd.Period("2011-01-03")])
+ left = PeriodIndex([Period("2011-01-01"), pd.NaT, Period("2011-01-03")])
+ right = PeriodIndex([pd.NaT, pd.NaT, Period("2011-01-03")])
if dtype is not None:
left = left.astype(dtype)
@@ -440,7 +438,7 @@ class TestPeriodIndexSeriesComparisonConsistency:
def _check(self, values, func, expected):
# Test PeriodIndex and Period Series Ops consistency
- idx = pd.PeriodIndex(values)
+ idx = PeriodIndex(values)
result = func(idx)
# check that we don't pass an unwanted type to tm.assert_equal
@@ -458,27 +456,27 @@ def test_pi_comp_period(self):
["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
)
- f = lambda x: x == pd.Period("2011-03", freq="M")
+ f = lambda x: x == Period("2011-03", freq="M")
exp = np.array([False, False, True, False], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") == x
+ f = lambda x: Period("2011-03", freq="M") == x
self._check(idx, f, exp)
- f = lambda x: x != pd.Period("2011-03", freq="M")
+ f = lambda x: x != Period("2011-03", freq="M")
exp = np.array([True, True, False, True], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") != x
+ f = lambda x: Period("2011-03", freq="M") != x
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") >= x
+ f = lambda x: Period("2011-03", freq="M") >= x
exp = np.array([True, True, True, False], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: x > pd.Period("2011-03", freq="M")
+ f = lambda x: x > Period("2011-03", freq="M")
exp = np.array([False, False, False, True], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") >= x
+ f = lambda x: Period("2011-03", freq="M") >= x
exp = np.array([True, True, True, False], dtype=np.bool_)
self._check(idx, f, exp)
@@ -487,10 +485,10 @@ def test_pi_comp_period_nat(self):
["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
)
- f = lambda x: x == pd.Period("2011-03", freq="M")
+ f = lambda x: x == Period("2011-03", freq="M")
exp = np.array([False, False, True, False], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") == x
+ f = lambda x: Period("2011-03", freq="M") == x
self._check(idx, f, exp)
f = lambda x: x == pd.NaT
@@ -499,10 +497,10 @@ def test_pi_comp_period_nat(self):
f = lambda x: pd.NaT == x
self._check(idx, f, exp)
- f = lambda x: x != pd.Period("2011-03", freq="M")
+ f = lambda x: x != Period("2011-03", freq="M")
exp = np.array([True, True, False, True], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") != x
+ f = lambda x: Period("2011-03", freq="M") != x
self._check(idx, f, exp)
f = lambda x: x != pd.NaT
@@ -511,11 +509,11 @@ def test_pi_comp_period_nat(self):
f = lambda x: pd.NaT != x
self._check(idx, f, exp)
- f = lambda x: pd.Period("2011-03", freq="M") >= x
+ f = lambda x: Period("2011-03", freq="M") >= x
exp = np.array([True, False, True, False], dtype=np.bool_)
self._check(idx, f, exp)
- f = lambda x: x < pd.Period("2011-03", freq="M")
+ f = lambda x: x < Period("2011-03", freq="M")
exp = np.array([True, False, False, False], dtype=np.bool_)
self._check(idx, f, exp)
@@ -537,14 +535,14 @@ def test_ops_frame_period(self):
# GH#13043
df = pd.DataFrame(
{
- "A": [pd.Period("2015-01", freq="M"), pd.Period("2015-02", freq="M")],
- "B": [pd.Period("2014-01", freq="M"), pd.Period("2014-02", freq="M")],
+ "A": [Period("2015-01", freq="M"), Period("2015-02", freq="M")],
+ "B": [Period("2014-01", freq="M"), Period("2014-02", freq="M")],
}
)
assert df["A"].dtype == "Period[M]"
assert df["B"].dtype == "Period[M]"
- p = pd.Period("2015-03", freq="M")
+ p = Period("2015-03", freq="M")
off = p.freq
# dtype will be object because of original dtype
exp = pd.DataFrame(
@@ -558,8 +556,8 @@ def test_ops_frame_period(self):
df2 = pd.DataFrame(
{
- "A": [pd.Period("2015-05", freq="M"), pd.Period("2015-06", freq="M")],
- "B": [pd.Period("2015-05", freq="M"), pd.Period("2015-06", freq="M")],
+ "A": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
+ "B": [Period("2015-05", freq="M"), Period("2015-06", freq="M")],
}
)
assert df2["A"].dtype == "Period[M]"
@@ -640,10 +638,10 @@ def test_sub_n_gt_1_ticks(self, tick_classes, n):
# GH 23878
p1_d = "19910905"
p2_d = "19920406"
- p1 = pd.PeriodIndex([p1_d], freq=tick_classes(n))
- p2 = pd.PeriodIndex([p2_d], freq=tick_classes(n))
+ p1 = PeriodIndex([p1_d], freq=tick_classes(n))
+ p2 = PeriodIndex([p2_d], freq=tick_classes(n))
- expected = pd.PeriodIndex([p2_d], freq=p2.freq.base) - pd.PeriodIndex(
+ expected = PeriodIndex([p2_d], freq=p2.freq.base) - PeriodIndex(
[p1_d], freq=p1.freq.base
)
@@ -665,11 +663,11 @@ def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
p1_d = "19910905"
p2_d = "19920406"
freq = offset(n, normalize=False, **kwds)
- p1 = pd.PeriodIndex([p1_d], freq=freq)
- p2 = pd.PeriodIndex([p2_d], freq=freq)
+ p1 = PeriodIndex([p1_d], freq=freq)
+ p2 = PeriodIndex([p2_d], freq=freq)
result = p2 - p1
- expected = pd.PeriodIndex([p2_d], freq=freq.base) - pd.PeriodIndex(
+ expected = PeriodIndex([p2_d], freq=freq.base) - PeriodIndex(
[p1_d], freq=freq.base
)
@@ -825,14 +823,14 @@ def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq):
@pytest.mark.parametrize("box", [np.array, pd.Index])
def test_pi_add_offset_array(self, box):
# GH#18849
- pi = pd.PeriodIndex([pd.Period("2015Q1"), pd.Period("2016Q2")])
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
offs = box(
[
pd.offsets.QuarterEnd(n=1, startingMonth=12),
pd.offsets.QuarterEnd(n=-2, startingMonth=12),
]
)
- expected = pd.PeriodIndex([pd.Period("2015Q2"), pd.Period("2015Q4")])
+ expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")])
with tm.assert_produces_warning(PerformanceWarning):
res = pi + offs
@@ -856,7 +854,7 @@ def test_pi_add_offset_array(self, box):
@pytest.mark.parametrize("box", [np.array, pd.Index])
def test_pi_sub_offset_array(self, box):
# GH#18824
- pi = pd.PeriodIndex([pd.Period("2015Q1"), pd.Period("2016Q2")])
+ pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
other = box(
[
pd.offsets.QuarterEnd(n=1, startingMonth=12),
@@ -934,10 +932,10 @@ def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
# GH#23215
# add offset to PeriodIndex with freq.n > 1
- per = pd.Period("2016-01", freq="2M")
- pi = pd.PeriodIndex([per])
+ per = Period("2016-01", freq="2M")
+ pi = PeriodIndex([per])
- expected = pd.PeriodIndex(["2016-03"], freq="2M")
+ expected = PeriodIndex(["2016-03"], freq="2M")
pi = tm.box_expected(pi, box_with_array, transpose=transpose)
expected = tm.box_expected(expected, box_with_array, transpose=transpose)
@@ -951,8 +949,8 @@ def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
# GH#23215
# PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0
- pi = pd.PeriodIndex(["2016-01"], freq="2M")
- expected = pd.PeriodIndex(["2016-04"], freq="2M")
+ pi = PeriodIndex(["2016-01"], freq="2M")
+ expected = PeriodIndex(["2016-04"], freq="2M")
pi = tm.box_expected(pi, box_with_array)
expected = tm.box_expected(expected, box_with_array)
@@ -970,21 +968,21 @@ def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
@pytest.mark.parametrize("op", [operator.add, ops.radd])
def test_pi_add_intarray(self, int_holder, op):
# GH#19959
- pi = pd.PeriodIndex([pd.Period("2015Q1"), pd.Period("NaT")])
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
other = int_holder([4, -1])
result = op(pi, other)
- expected = pd.PeriodIndex([pd.Period("2016Q1"), pd.Period("NaT")])
+ expected = PeriodIndex([Period("2016Q1"), Period("NaT")])
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("int_holder", [np.array, pd.Index])
def test_pi_sub_intarray(self, int_holder):
# GH#19959
- pi = pd.PeriodIndex([pd.Period("2015Q1"), pd.Period("NaT")])
+ pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
other = int_holder([4, -1])
result = pi - other
- expected = pd.PeriodIndex([pd.Period("2014Q1"), pd.Period("NaT")])
+ expected = PeriodIndex([Period("2014Q1"), Period("NaT")])
tm.assert_index_equal(result, expected)
msg = r"bad operand type for unary -: 'PeriodArray'"
@@ -1003,7 +1001,7 @@ def test_pi_add_timedeltalike_minute_gt1(self, three_days):
other = three_days
rng = pd.period_range("2014-05-01", periods=3, freq="2D")
- expected = pd.PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D")
+ expected = PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D")
result = rng + other
tm.assert_index_equal(result, expected)
@@ -1012,7 +1010,7 @@ def test_pi_add_timedeltalike_minute_gt1(self, three_days):
tm.assert_index_equal(result, expected)
# subtraction
- expected = pd.PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D")
+ expected = PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D")
result = rng - other
tm.assert_index_equal(result, expected)
@@ -1170,7 +1168,7 @@ def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
# GH#23320 special handling for timedelta64("NaT")
pi = pd.period_range("1994-04-01", periods=9, freq="19D")
other = np.timedelta64("NaT")
- expected = pd.PeriodIndex(["NaT"] * 9, freq="19D")
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array, transpose=transpose)
expected = tm.box_expected(expected, box_with_array, transpose=transpose)
@@ -1194,7 +1192,7 @@ def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
)
def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other):
pi = pd.period_range("1994-04-01", periods=9, freq="19D")
- expected = pd.PeriodIndex(["NaT"] * 9, freq="19D")
+ expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array)
expected = tm.box_expected(expected, box_with_array)
@@ -1230,7 +1228,7 @@ def test_parr_add_sub_object_array(self):
with tm.assert_produces_warning(PerformanceWarning):
result = parr + other
- expected = pd.PeriodIndex(
+ expected = PeriodIndex(
["2001-01-01", "2001-01-03", "2001-01-05"], freq="D"
).array
tm.assert_equal(result, expected)
@@ -1238,7 +1236,7 @@ def test_parr_add_sub_object_array(self):
with tm.assert_produces_warning(PerformanceWarning):
result = parr - other
- expected = pd.PeriodIndex(["2000-12-30"] * 3, freq="D").array
+ expected = PeriodIndex(["2000-12-30"] * 3, freq="D").array
tm.assert_equal(result, expected)
@@ -1246,13 +1244,13 @@ class TestPeriodSeriesArithmetic:
def test_ops_series_timedelta(self):
# GH#13043
ser = Series(
- [pd.Period("2015-01-01", freq="D"), pd.Period("2015-01-02", freq="D")],
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
name="xxx",
)
assert ser.dtype == "Period[D]"
expected = Series(
- [pd.Period("2015-01-02", freq="D"), pd.Period("2015-01-03", freq="D")],
+ [Period("2015-01-02", freq="D"), Period("2015-01-03", freq="D")],
name="xxx",
)
@@ -1271,12 +1269,12 @@ def test_ops_series_timedelta(self):
def test_ops_series_period(self):
# GH#13043
ser = Series(
- [pd.Period("2015-01-01", freq="D"), pd.Period("2015-01-02", freq="D")],
+ [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")],
name="xxx",
)
assert ser.dtype == "Period[D]"
- per = pd.Period("2015-01-10", freq="D")
+ per = Period("2015-01-10", freq="D")
off = per.freq
# dtype will be object because of original dtype
expected = Series([9 * off, 8 * off], name="xxx", dtype=object)
@@ -1284,7 +1282,7 @@ def test_ops_series_period(self):
tm.assert_series_equal(ser - per, -1 * expected)
s2 = Series(
- [pd.Period("2015-01-05", freq="D"), pd.Period("2015-01-04", freq="D")],
+ [Period("2015-01-05", freq="D"), Period("2015-01-04", freq="D")],
name="xxx",
)
assert s2.dtype == "Period[D]"
@@ -1298,7 +1296,7 @@ class TestPeriodIndexSeriesMethods:
""" Test PeriodIndex and Period Series Ops consistency """
def _check(self, values, func, expected):
- idx = pd.PeriodIndex(values)
+ idx = PeriodIndex(values)
result = func(idx)
tm.assert_equal(result, expected)
@@ -1475,27 +1473,27 @@ def test_pi_sub_period(self):
["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx"
)
- result = idx - pd.Period("2012-01", freq="M")
+ result = idx - Period("2012-01", freq="M")
off = idx.freq
exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name="idx")
tm.assert_index_equal(result, exp)
- result = np.subtract(idx, pd.Period("2012-01", freq="M"))
+ result = np.subtract(idx, Period("2012-01", freq="M"))
tm.assert_index_equal(result, exp)
- result = pd.Period("2012-01", freq="M") - idx
+ result = Period("2012-01", freq="M") - idx
exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name="idx")
tm.assert_index_equal(result, exp)
- result = np.subtract(pd.Period("2012-01", freq="M"), idx)
+ result = np.subtract(Period("2012-01", freq="M"), idx)
tm.assert_index_equal(result, exp)
exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
- result = idx - pd.Period("NaT", freq="M")
+ result = idx - Period("NaT", freq="M")
tm.assert_index_equal(result, exp)
assert result.freq == exp.freq
- result = pd.Period("NaT", freq="M") - idx
+ result = Period("NaT", freq="M") - idx
tm.assert_index_equal(result, exp)
assert result.freq == exp.freq
@@ -1514,23 +1512,23 @@ def test_pi_sub_period_nat(self):
["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx"
)
- result = idx - pd.Period("2012-01", freq="M")
+ result = idx - Period("2012-01", freq="M")
off = idx.freq
exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name="idx")
tm.assert_index_equal(result, exp)
- result = pd.Period("2012-01", freq="M") - idx
+ result = Period("2012-01", freq="M") - idx
exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name="idx")
tm.assert_index_equal(result, exp)
exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
- tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp)
- tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp)
+ tm.assert_index_equal(idx - Period("NaT", freq="M"), exp)
+ tm.assert_index_equal(Period("NaT", freq="M") - idx, exp)
@pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None])
def test_comparison_operations(self, scalars):
# GH 28980
expected = Series([False, False])
- s = Series([pd.Period("2019"), pd.Period("2020")], dtype="period[A-DEC]")
+ s = Series([Period("2019"), Period("2020")], dtype="period[A-DEC]")
result = s == scalars
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/arrays/floating/test_construction.py b/pandas/tests/arrays/floating/test_construction.py
index 69147f8f3a54a..a3eade98d99d6 100644
--- a/pandas/tests/arrays/floating/test_construction.py
+++ b/pandas/tests/arrays/floating/test_construction.py
@@ -8,7 +8,7 @@
def test_uses_pandas_na():
- a = pd.array([1, None], dtype=pd.Float64Dtype())
+ a = pd.array([1, None], dtype=Float64Dtype())
assert a[1] is pd.NA
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 16b4dd5c95932..8cd0d29a34ec8 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -200,10 +200,10 @@ def test_update_dtype_raises(original, dtype, expected_error_msg):
def test_repr():
# GH-34352
- result = str(pd.SparseDtype("int64", fill_value=0))
+ result = str(SparseDtype("int64", fill_value=0))
expected = "Sparse[int64, 0]"
assert result == expected
- result = str(pd.SparseDtype(object, fill_value="0"))
+ result = str(SparseDtype(object, fill_value="0"))
expected = "Sparse[object, '0']"
assert result == expected
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index c24f789b30313..94a5406eb1f8f 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -31,7 +31,7 @@ def period_index(freqstr):
the PeriodIndex behavior.
"""
# TODO: non-monotone indexes; NaTs, different start dates
- pi = pd.period_range(start=pd.Timestamp("2000-01-01"), periods=100, freq=freqstr)
+ pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
return pi
@@ -45,7 +45,7 @@ def datetime_index(freqstr):
the DatetimeIndex behavior.
"""
# TODO: non-monotone indexes; NaTs, different start dates, timezones
- dti = pd.date_range(start=pd.Timestamp("2000-01-01"), periods=100, freq=freqstr)
+ dti = pd.date_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
return dti
@@ -58,7 +58,7 @@ def timedelta_index():
the TimedeltaIndex behavior.
"""
# TODO: flesh this out
- return pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])
+ return TimedeltaIndex(["1 Day", "3 Hours", "NaT"])
class SharedTests:
@@ -139,7 +139,7 @@ def test_take(self):
tm.assert_index_equal(self.index_cls(result), expected)
- @pytest.mark.parametrize("fill_value", [2, 2.0, pd.Timestamp.now().time])
+ @pytest.mark.parametrize("fill_value", [2, 2.0, Timestamp.now().time])
def test_take_fill_raises(self, fill_value):
data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
@@ -539,7 +539,7 @@ def test_median(self, arr1d):
class TestDatetimeArray(SharedTests):
index_cls = pd.DatetimeIndex
array_cls = DatetimeArray
- dtype = pd.Timestamp
+ dtype = Timestamp
@pytest.fixture
def arr1d(self, tz_naive_fixture, freqstr):
@@ -741,7 +741,7 @@ def test_take_fill_valid(self, arr1d):
arr = arr1d
dti = self.index_cls(arr1d)
- now = pd.Timestamp.now().tz_localize(dti.tz)
+ now = Timestamp.now().tz_localize(dti.tz)
result = arr.take([-1, 1], allow_fill=True, fill_value=now)
assert result[0] == now
@@ -752,10 +752,10 @@ def test_take_fill_valid(self, arr1d):
with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
- arr.take([-1, 1], allow_fill=True, fill_value=pd.Period("2014Q1"))
+ arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1"))
tz = None if dti.tz is not None else "US/Eastern"
- now = pd.Timestamp.now().tz_localize(tz)
+ now = Timestamp.now().tz_localize(tz)
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
# Timestamp with mismatched tz-awareness
@@ -828,22 +828,22 @@ def test_strftime_nat(self):
class TestTimedeltaArray(SharedTests):
- index_cls = pd.TimedeltaIndex
+ index_cls = TimedeltaIndex
array_cls = TimedeltaArray
dtype = pd.Timedelta
def test_from_tdi(self):
- tdi = pd.TimedeltaIndex(["1 Day", "3 Hours"])
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
arr = TimedeltaArray(tdi)
assert list(arr) == list(tdi)
# Check that Index.__new__ knows what to do with TimedeltaArray
tdi2 = pd.Index(arr)
- assert isinstance(tdi2, pd.TimedeltaIndex)
+ assert isinstance(tdi2, TimedeltaIndex)
assert list(tdi2) == list(arr)
def test_astype_object(self):
- tdi = pd.TimedeltaIndex(["1 Day", "3 Hours"])
+ tdi = TimedeltaIndex(["1 Day", "3 Hours"])
arr = TimedeltaArray(tdi)
asobj = arr.astype("O")
assert isinstance(asobj, np.ndarray)
@@ -868,7 +868,7 @@ def test_total_seconds(self, timedelta_index):
tm.assert_numpy_array_equal(result, expected.values)
- @pytest.mark.parametrize("propname", pd.TimedeltaIndex._field_ops)
+ @pytest.mark.parametrize("propname", TimedeltaIndex._field_ops)
def test_int_properties(self, timedelta_index, propname):
tdi = timedelta_index
arr = TimedeltaArray(tdi)
@@ -928,7 +928,7 @@ def test_take_fill_valid(self, timedelta_index):
result = arr.take([-1, 1], allow_fill=True, fill_value=td1)
assert result[0] == td1
- now = pd.Timestamp.now()
+ now = Timestamp.now()
value = now
msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
with pytest.raises(TypeError, match=msg):
@@ -947,9 +947,9 @@ def test_take_fill_valid(self, timedelta_index):
class TestPeriodArray(SharedTests):
- index_cls = pd.PeriodIndex
+ index_cls = PeriodIndex
array_cls = PeriodArray
- dtype = pd.Period
+ dtype = Period
@pytest.fixture
def arr1d(self, period_index):
@@ -962,7 +962,7 @@ def test_from_pi(self, arr1d):
# Check that Index.__new__ knows what to do with PeriodArray
pi2 = pd.Index(arr)
- assert isinstance(pi2, pd.PeriodIndex)
+ assert isinstance(pi2, PeriodIndex)
assert list(pi2) == list(arr)
def test_astype_object(self, arr1d):
@@ -1075,7 +1075,7 @@ def test_strftime_nat(self):
"array,casting_nats",
[
(
- pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
(pd.NaT, np.timedelta64("NaT", "ns")),
),
(
@@ -1099,7 +1099,7 @@ def test_casting_nat_setitem_array(array, casting_nats):
"array,non_casting_nats",
[
(
- pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
+ TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
(np.datetime64("NaT", "ns"), pd.NaT.value),
),
(
@@ -1164,8 +1164,8 @@ def test_to_numpy_extra(array):
"values",
[
pd.to_datetime(["2020-01-01", "2020-02-01"]),
- pd.TimedeltaIndex([1, 2], unit="D"),
- pd.PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
+ TimedeltaIndex([1, 2], unit="D"),
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
],
)
@pytest.mark.parametrize(
@@ -1195,12 +1195,12 @@ def test_searchsorted_datetimelike_with_listlike(values, klass, as_index):
"values",
[
pd.to_datetime(["2020-01-01", "2020-02-01"]),
- pd.TimedeltaIndex([1, 2], unit="D"),
- pd.PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
+ TimedeltaIndex([1, 2], unit="D"),
+ PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"),
],
)
@pytest.mark.parametrize(
- "arg", [[1, 2], ["a", "b"], [pd.Timestamp("2020-01-01", tz="Europe/London")] * 2]
+ "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
)
def test_searchsorted_datetimelike_with_listlike_invalid_dtype(values, arg):
# https://github.com/pandas-dev/pandas/issues/32762
diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py
index 45089fd876ffc..0f1cb55b9811c 100644
--- a/pandas/tests/indexes/categorical/test_formats.py
+++ b/pandas/tests/indexes/categorical/test_formats.py
@@ -3,18 +3,18 @@
"""
import pandas._config.config as cf
-import pandas as pd
+from pandas import CategoricalIndex
class TestCategoricalIndexRepr:
def test_string_categorical_index_repr(self):
# short
- idx = pd.CategoricalIndex(["a", "bb", "ccc"])
+ idx = CategoricalIndex(["a", "bb", "ccc"])
expected = """CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa
assert repr(idx) == expected
# multiple lines
- idx = pd.CategoricalIndex(["a", "bb", "ccc"] * 10)
+ idx = CategoricalIndex(["a", "bb", "ccc"] * 10)
expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb',
'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
@@ -23,7 +23,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# truncated
- idx = pd.CategoricalIndex(["a", "bb", "ccc"] * 100)
+ idx = CategoricalIndex(["a", "bb", "ccc"] * 100)
expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
...
'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
@@ -32,7 +32,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# larger categories
- idx = pd.CategoricalIndex(list("abcdefghijklmmo"))
+ idx = CategoricalIndex(list("abcdefghijklmmo"))
expected = """CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'm', 'o'],
categories=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', ...], ordered=False, dtype='category')""" # noqa
@@ -40,12 +40,12 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# short
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"])
+ idx = CategoricalIndex(["あ", "いい", "ううう"])
expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa
assert repr(idx) == expected
# multiple lines
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 10)
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 10)
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
@@ -54,7 +54,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# truncated
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 100)
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 100)
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
...
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
@@ -63,7 +63,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# larger categories
- idx = pd.CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
+ idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し',
'す', 'せ', 'そ'],
categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')""" # noqa
@@ -74,12 +74,12 @@ def test_string_categorical_index_repr(self):
with cf.option_context("display.unicode.east_asian_width", True):
# short
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"])
+ idx = CategoricalIndex(["あ", "いい", "ううう"])
expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa
assert repr(idx) == expected
# multiple lines
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 10)
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 10)
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
@@ -89,7 +89,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# truncated
- idx = pd.CategoricalIndex(["あ", "いい", "ううう"] * 100)
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 100)
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
'ううう', 'あ',
...
@@ -100,7 +100,7 @@ def test_string_categorical_index_repr(self):
assert repr(idx) == expected
# larger categories
- idx = pd.CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
+ idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ',
'さ', 'し', 'す', 'せ', 'そ'],
categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')""" # noqa
diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py
index 3aa8710c6a6c8..9f4b7f7bad10f 100644
--- a/pandas/tests/indexes/categorical/test_indexing.py
+++ b/pandas/tests/indexes/categorical/test_indexing.py
@@ -11,30 +11,30 @@ def test_take_fill_value(self):
# GH 12631
# numeric category
- idx = pd.CategoricalIndex([1, 2, 3], name="xxx")
+ idx = CategoricalIndex([1, 2, 3], name="xxx")
result = idx.take(np.array([1, 0, -1]))
- expected = pd.CategoricalIndex([2, 1, 3], name="xxx")
+ expected = CategoricalIndex([2, 1, 3], name="xxx")
tm.assert_index_equal(result, expected)
tm.assert_categorical_equal(result.values, expected.values)
# fill_value
result = idx.take(np.array([1, 0, -1]), fill_value=True)
- expected = pd.CategoricalIndex([2, 1, np.nan], categories=[1, 2, 3], name="xxx")
+ expected = CategoricalIndex([2, 1, np.nan], categories=[1, 2, 3], name="xxx")
tm.assert_index_equal(result, expected)
tm.assert_categorical_equal(result.values, expected.values)
# allow_fill=False
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
- expected = pd.CategoricalIndex([2, 1, 3], name="xxx")
+ expected = CategoricalIndex([2, 1, 3], name="xxx")
tm.assert_index_equal(result, expected)
tm.assert_categorical_equal(result.values, expected.values)
# object category
- idx = pd.CategoricalIndex(
+ idx = CategoricalIndex(
list("CBA"), categories=list("ABC"), ordered=True, name="xxx"
)
result = idx.take(np.array([1, 0, -1]))
- expected = pd.CategoricalIndex(
+ expected = CategoricalIndex(
list("BCA"), categories=list("ABC"), ordered=True, name="xxx"
)
tm.assert_index_equal(result, expected)
@@ -42,7 +42,7 @@ def test_take_fill_value(self):
# fill_value
result = idx.take(np.array([1, 0, -1]), fill_value=True)
- expected = pd.CategoricalIndex(
+ expected = CategoricalIndex(
["B", "C", np.nan], categories=list("ABC"), ordered=True, name="xxx"
)
tm.assert_index_equal(result, expected)
@@ -50,7 +50,7 @@ def test_take_fill_value(self):
# allow_fill=False
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
- expected = pd.CategoricalIndex(
+ expected = CategoricalIndex(
list("BCA"), categories=list("ABC"), ordered=True, name="xxx"
)
tm.assert_index_equal(result, expected)
@@ -73,19 +73,19 @@ def test_take_fill_value_datetime(self):
# datetime category
idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx")
- idx = pd.CategoricalIndex(idx)
+ idx = CategoricalIndex(idx)
result = idx.take(np.array([1, 0, -1]))
expected = pd.DatetimeIndex(
["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx"
)
- expected = pd.CategoricalIndex(expected)
+ expected = CategoricalIndex(expected)
tm.assert_index_equal(result, expected)
# fill_value
result = idx.take(np.array([1, 0, -1]), fill_value=True)
expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx")
exp_cats = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"])
- expected = pd.CategoricalIndex(expected, categories=exp_cats)
+ expected = CategoricalIndex(expected, categories=exp_cats)
tm.assert_index_equal(result, expected)
# allow_fill=False
@@ -93,7 +93,7 @@ def test_take_fill_value_datetime(self):
expected = pd.DatetimeIndex(
["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx"
)
- expected = pd.CategoricalIndex(expected)
+ expected = CategoricalIndex(expected)
tm.assert_index_equal(result, expected)
msg = (
@@ -110,7 +110,7 @@ def test_take_fill_value_datetime(self):
idx.take(np.array([1, -5]))
def test_take_invalid_kwargs(self):
- idx = pd.CategoricalIndex([1, 2, 3], name="foo")
+ idx = CategoricalIndex([1, 2, 3], name="foo")
indices = [1, 0, -1]
msg = r"take\(\) got an unexpected keyword argument 'foo'"
@@ -175,18 +175,18 @@ def test_get_loc(self):
i.get_loc("c")
def test_get_loc_unique(self):
- cidx = pd.CategoricalIndex(list("abc"))
+ cidx = CategoricalIndex(list("abc"))
result = cidx.get_loc("b")
assert result == 1
def test_get_loc_monotonic_nonunique(self):
- cidx = pd.CategoricalIndex(list("abbc"))
+ cidx = CategoricalIndex(list("abbc"))
result = cidx.get_loc("b")
expected = slice(1, 3, None)
assert result == expected
def test_get_loc_nonmonotonic_nonunique(self):
- cidx = pd.CategoricalIndex(list("abcb"))
+ cidx = CategoricalIndex(list("abcb"))
result = cidx.get_loc("b")
expected = np.array([False, True, False, True], dtype=bool)
tm.assert_numpy_array_equal(result, expected)
@@ -368,7 +368,7 @@ def test_contains_interval(self, item, expected):
def test_contains_list(self):
# GH#21729
- idx = pd.CategoricalIndex([1, 2, 3])
+ idx = CategoricalIndex([1, 2, 3])
assert "a" not in idx
diff --git a/pandas/tests/indexes/ranges/test_indexing.py b/pandas/tests/indexes/ranges/test_indexing.py
index 238c33c3db6d7..5b662dbed1238 100644
--- a/pandas/tests/indexes/ranges/test_indexing.py
+++ b/pandas/tests/indexes/ranges/test_indexing.py
@@ -53,7 +53,7 @@ def test_take_preserve_name(self):
def test_take_fill_value(self):
# GH#12631
- idx = pd.RangeIndex(1, 4, name="xxx")
+ idx = RangeIndex(1, 4, name="xxx")
result = idx.take(np.array([1, 0, -1]))
expected = pd.Int64Index([2, 1, 3], name="xxx")
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 788b6f99806d6..ec03d5466d1f0 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -221,7 +221,7 @@ def test_constructor_no_pandas_array(self):
@pytest.mark.parametrize(
"klass,dtype,na_val",
[
- (pd.Float64Index, np.float64, np.nan),
+ (Float64Index, np.float64, np.nan),
(DatetimeIndex, "datetime64[ns]", pd.NaT),
],
)
@@ -411,7 +411,7 @@ def test_constructor_empty(self, value, klass):
(PeriodIndex([], freq="B"), PeriodIndex),
(PeriodIndex(iter([]), freq="B"), PeriodIndex),
(PeriodIndex((_ for _ in []), freq="B"), PeriodIndex),
- (RangeIndex(step=1), pd.RangeIndex),
+ (RangeIndex(step=1), RangeIndex),
(MultiIndex(levels=[[1, 2], ["blue", "red"]], codes=[[], []]), MultiIndex),
],
)
@@ -1982,7 +1982,7 @@ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):
"labels,dtype",
[
(pd.Int64Index([]), np.int64),
- (pd.Float64Index([]), np.float64),
+ (Float64Index([]), np.float64),
(DatetimeIndex([]), np.datetime64),
],
)
@@ -1994,7 +1994,7 @@ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dty
def test_reindex_no_type_preserve_target_empty_mi(self):
index = Index(list("abc"))
result = index.reindex(
- MultiIndex([pd.Int64Index([]), pd.Float64Index([])], [[], []])
+ MultiIndex([pd.Int64Index([]), Float64Index([])], [[], []])
)[0]
assert result.levels[0].dtype.type == np.int64
assert result.levels[1].dtype.type == np.float64
@@ -2342,12 +2342,12 @@ def test_dropna(self, how, dtype, vals, expected):
pd.TimedeltaIndex(["1 days", "2 days", "3 days"]),
),
(
- pd.PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
- pd.PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
),
(
- pd.PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"),
- pd.PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"),
+ PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
),
],
)
@@ -2517,7 +2517,7 @@ def test_deprecated_fastpath():
pd.Int64Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True)
with pytest.raises(TypeError, match=msg):
- pd.RangeIndex(0, 5, 2, name="test", fastpath=True)
+ RangeIndex(0, 5, 2, name="test", fastpath=True)
with pytest.raises(TypeError, match=msg):
pd.CategoricalIndex(["a", "b", "c"], name="test", fastpath=True)
@@ -2544,7 +2544,7 @@ def test_validate_1d_input():
Index(arr)
with pytest.raises(ValueError, match=msg):
- pd.Float64Index(arr.astype(np.float64))
+ Float64Index(arr.astype(np.float64))
with pytest.raises(ValueError, match=msg):
pd.Int64Index(arr.astype(np.int64))
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index d76a5a6f64055..32d1cf82c4330 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -302,7 +302,7 @@ def create_h5_and_return_checksum(track_times):
with ensure_clean_path(setup_path) as path:
df = DataFrame({"a": [1]})
- with pd.HDFStore(path, mode="w") as hdf:
+ with HDFStore(path, mode="w") as hdf:
hdf.put(
"table",
df,
@@ -843,7 +843,7 @@ def test_complibs_default_settings(self, setup_path):
# Check if file-defaults can be overridden on a per table basis
with ensure_clean_path(setup_path) as tmpfile:
- store = pd.HDFStore(tmpfile)
+ store = HDFStore(tmpfile)
store.append("dfc", df, complevel=9, complib="blosc")
store.append("df", df)
store.close()
@@ -1298,7 +1298,7 @@ def test_read_missing_key_opened_store(self, setup_path):
df = DataFrame({"a": range(2), "b": range(2)})
df.to_hdf(path, "k1")
- with pd.HDFStore(path, "r") as store:
+ with HDFStore(path, "r") as store:
with pytest.raises(KeyError, match="'No object named k2 in the file'"):
pd.read_hdf(store, "k2")
@@ -3935,11 +3935,11 @@ def test_path_pathlib_hdfstore(self, setup_path):
df = tm.makeDataFrame()
def writer(path):
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
df.to_hdf(store, "df")
def reader(path):
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
return pd.read_hdf(store, "df")
result = tm.round_trip_pathlib(writer, reader)
@@ -3956,11 +3956,11 @@ def test_path_localpath_hdfstore(self, setup_path):
df = tm.makeDataFrame()
def writer(path):
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
df.to_hdf(store, "df")
def reader(path):
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
return pd.read_hdf(store, "df")
result = tm.round_trip_localpath(writer, reader)
@@ -4829,7 +4829,7 @@ def test_read_hdf_series_mode_r(self, format, setup_path):
def test_fspath(self):
with tm.ensure_clean("foo.h5") as path:
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
assert os.fspath(store) == str(path)
def test_read_py2_hdf_file_in_py3(self, datapath):
@@ -4867,7 +4867,7 @@ def test_select_empty_where(self, where):
df = DataFrame([1, 2, 3])
with ensure_clean_path("empty_where.h5") as path:
- with pd.HDFStore(path) as store:
+ with HDFStore(path) as store:
store.put("df", df, "t")
result = pd.read_hdf(store, "df", where=where)
tm.assert_frame_equal(result, df)
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py
index 46bc6421c2070..bce42f8c6caf0 100644
--- a/pandas/tests/scalar/period/test_period.py
+++ b/pandas/tests/scalar/period/test_period.py
@@ -491,7 +491,7 @@ def test_period_cons_combined(self):
def test_period_large_ordinal(self, hour):
# Issue #36430
# Integer overflow for Period over the maximum timestamp
- p = pd.Period(ordinal=2562048 + hour, freq="1H")
+ p = Period(ordinal=2562048 + hour, freq="1H")
assert p.hour == hour
@@ -652,7 +652,7 @@ def _ex(p):
assert result == expected
def test_to_timestamp_business_end(self):
- per = pd.Period("1990-01-05", "B") # Friday
+ per = Period("1990-01-05", "B") # Friday
result = per.to_timestamp("B", how="E")
expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)
| Additional fixes for MarcoGorelli/PyDataGlobal2020-sprint#1.
Continues the work of lpkirwin in #37838.
- [ ] 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/37842 | 2020-11-14T18:58:32Z | 2020-11-15T09:09:07Z | 2020-11-15T09:09:06Z | 2020-11-15T09:09:07Z |
CI: Skip test when no xlwt or openpyxl | diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py
index c5767c5080ddd..2dfd18cd67821 100644
--- a/pandas/tests/io/test_fsspec.py
+++ b/pandas/tests/io/test_fsspec.py
@@ -126,6 +126,11 @@ def test_csv_options(fsspectest):
@pytest.mark.parametrize("extension", ["xlsx", "xls"])
def test_excel_options(fsspectest, extension):
+ if extension == "xls":
+ pytest.importorskip("xlwt")
+ else:
+ pytest.importorskip("openpyxl")
+
df = DataFrame({"a": [0]})
path = f"testmem://test/test.{extension}"
| Ref: https://github.com/pandas-dev/pandas/pull/37818
Seeing error in CI: https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=47726&view=logs&j=acc1347f-8235-55b0-95c7-0e2189e61659&t=486f34f1-eda6-516a-fc5d-d8195128dacd
Skip logic same as `test_to_excel` in this file
cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/37841 | 2020-11-14T18:42:45Z | 2020-11-14T23:50:39Z | 2020-11-14T23:50:39Z | 2020-11-14T23:50:40Z |
TST: Add test for setting item using python list (#19406) | diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 4f00f9c931d6a..4ed7510a1d9e1 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -126,6 +126,15 @@ def test_setitem_boolean_different_order(self, string_series):
tm.assert_series_equal(copy, expected)
+ @pytest.mark.parametrize("func", [list, np.array, Series])
+ def test_setitem_boolean_python_list(self, func):
+ # GH19406
+ ser = Series([None, "b", None])
+ mask = func([True, False, True])
+ ser[mask] = ["a", "c"]
+ expected = Series(["a", "b", "c"])
+ tm.assert_series_equal(ser, expected)
+
@pytest.mark.parametrize("value", [None, NaT, np.nan])
def test_setitem_boolean_td64_values_cast_na(self, value):
# GH#18586
| - [X] closes #19406
- [X] tests added / passed
- [X] passes `black pandas`
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [NA] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37840 | 2020-11-14T18:29:33Z | 2020-11-15T09:12:13Z | 2020-11-15T09:12:13Z | 2020-11-15T13:44:22Z |
DOC: section in indexing user guide to show use of np.where | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 98c981539d207..da0b3a12f44b6 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -1158,6 +1158,40 @@ Mask
s.mask(s >= 0)
df.mask(df >= 0)
+.. _indexing.np_where:
+
+Setting with enlargement conditionally using :func:`numpy`
+----------------------------------------------------------
+
+An alternative to :meth:`~pandas.DataFrame.where` is to use :func:`numpy.where`.
+Combined with setting a new column, you can use it to enlarge a dataframe where the
+values are determined conditionally.
+
+Consider you have two choices to choose from in the following dataframe. And you want to
+set a new column color to 'green' when the second column has 'Z'. You can do the
+following:
+
+.. ipython:: python
+
+ df = pd.DataFrame({'col1': list('ABBC'), 'col2': list('ZZXY')})
+ df['color'] = np.where(df['col2'] == 'Z', 'green', 'red')
+ df
+
+If you have multiple conditions, you can use :func:`numpy.select` to achieve that. Say
+corresponding to three conditions there are three choice of colors, with a fourth color
+as a fallback, you can do the following.
+
+.. ipython:: python
+
+ conditions = [
+ (df['col2'] == 'Z') & (df['col1'] == 'A'),
+ (df['col2'] == 'Z') & (df['col1'] == 'B'),
+ (df['col1'] == 'B')
+ ]
+ choices = ['yellow', 'blue', 'purple']
+ df['color'] = np.select(conditions, choices, default='black')
+ df
+
.. _indexing.query:
The :meth:`~pandas.DataFrame.query` Method
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Add a section in the user guide to illustrate the use of `np.where` and `np.select` to enlarge a dataframe conditionally. The example is taken from SO, as mentioned in [this issue](https://github.com/MarcoGorelli/PyDataGlobal2020-sprint/issues/5#issuecomment-727241262). | https://api.github.com/repos/pandas-dev/pandas/pulls/37839 | 2020-11-14T18:28:22Z | 2020-11-18T13:58:35Z | 2020-11-18T13:58:35Z | 2020-11-18T19:14:12Z |
Fix cases of inconsistent namespacing in tests | diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index 47baf4e76f8c3..e81b919dbad2d 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -2,6 +2,7 @@
import pytest
import pandas as pd
+from pandas import Float64Index, Int64Index, RangeIndex, UInt64Index
import pandas._testing as tm
# ------------------------------------------------------------------
@@ -93,10 +94,10 @@ def zero(request):
@pytest.fixture(
params=[
- pd.Float64Index(np.arange(5, dtype="float64")),
- pd.Int64Index(np.arange(5, dtype="int64")),
- pd.UInt64Index(np.arange(5, dtype="uint64")),
- pd.RangeIndex(5),
+ Float64Index(np.arange(5, dtype="float64")),
+ Int64Index(np.arange(5, dtype="int64")),
+ UInt64Index(np.arange(5, dtype="uint64")),
+ RangeIndex(5),
],
ids=lambda x: type(x).__name__,
)
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index b0b8f1345e4d3..35ffb0a246e25 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -17,6 +17,7 @@
import pandas as pd
from pandas import (
+ DateOffset,
DatetimeIndex,
NaT,
Period,
@@ -166,8 +167,8 @@ class TestDatetime64SeriesComparison:
[NaT, NaT, Timedelta("3 days")],
),
(
- [pd.Period("2011-01", freq="M"), NaT, pd.Period("2011-03", freq="M")],
- [NaT, NaT, pd.Period("2011-03", freq="M")],
+ [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
+ [NaT, NaT, Period("2011-03", freq="M")],
),
],
)
@@ -1078,7 +1079,7 @@ def test_dt64arr_add_timestamp_raises(self, box_with_array):
3.14,
np.array([2.0, 3.0]),
# GH#13078 datetime +/- Period is invalid
- pd.Period("2011-01-01", freq="D"),
+ Period("2011-01-01", freq="D"),
# https://github.com/pandas-dev/pandas/issues/10329
time(1, 2, 3),
],
@@ -1288,7 +1289,7 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):
("microseconds", 5),
]
for i, kwd in enumerate(relative_kwargs):
- off = pd.DateOffset(**dict([kwd]))
+ off = DateOffset(**dict([kwd]))
expected = DatetimeIndex([x + off for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
@@ -1298,7 +1299,7 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, vec - off)
- off = pd.DateOffset(**dict(relative_kwargs[: i + 1]))
+ off = DateOffset(**dict(relative_kwargs[: i + 1]))
expected = DatetimeIndex([x + off for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
@@ -1431,14 +1432,14 @@ def test_dt64arr_add_sub_DateOffset(self, box_with_array):
# GH#10699
s = date_range("2000-01-01", "2000-01-31", name="a")
s = tm.box_expected(s, box_with_array)
- result = s + pd.DateOffset(years=1)
- result2 = pd.DateOffset(years=1) + s
+ result = s + DateOffset(years=1)
+ result2 = DateOffset(years=1) + s
exp = date_range("2001-01-01", "2001-01-31", name="a")._with_freq(None)
exp = tm.box_expected(exp, box_with_array)
tm.assert_equal(result, exp)
tm.assert_equal(result2, exp)
- result = s - pd.DateOffset(years=1)
+ result = s - DateOffset(years=1)
exp = date_range("1999-01-01", "1999-01-31", name="a")._with_freq(None)
exp = tm.box_expected(exp, box_with_array)
tm.assert_equal(result, exp)
@@ -1527,7 +1528,7 @@ def test_dt64arr_add_sub_offset_array(
[
(
"__add__",
- pd.DateOffset(months=3, days=10),
+ DateOffset(months=3, days=10),
[
Timestamp("2014-04-11"),
Timestamp("2015-04-11"),
@@ -1538,7 +1539,7 @@ def test_dt64arr_add_sub_offset_array(
),
(
"__add__",
- pd.DateOffset(months=3),
+ DateOffset(months=3),
[
Timestamp("2014-04-01"),
Timestamp("2015-04-01"),
@@ -1549,7 +1550,7 @@ def test_dt64arr_add_sub_offset_array(
),
(
"__sub__",
- pd.DateOffset(months=3, days=10),
+ DateOffset(months=3, days=10),
[
Timestamp("2013-09-21"),
Timestamp("2014-09-21"),
@@ -1560,7 +1561,7 @@ def test_dt64arr_add_sub_offset_array(
),
(
"__sub__",
- pd.DateOffset(months=3),
+ DateOffset(months=3),
[
Timestamp("2013-10-01"),
Timestamp("2014-10-01"),
diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py
index e0a4877da6c7e..15307b6f2190e 100644
--- a/pandas/tests/arrays/integer/test_construction.py
+++ b/pandas/tests/arrays/integer/test_construction.py
@@ -9,7 +9,7 @@
def test_uses_pandas_na():
- a = pd.array([1, None], dtype=pd.Int64Dtype())
+ a = pd.array([1, None], dtype=Int64Dtype())
assert a[1] is pd.NA
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index a2a9bb2c4b039..46edde62b510e 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -274,7 +274,7 @@ def test_take(self):
tm.assert_sp_array_equal(self.arr.take([0, 1, 2]), exp)
def test_take_all_empty(self):
- a = pd.array([0, 0], dtype=pd.SparseDtype("int64"))
+ a = pd.array([0, 0], dtype=SparseDtype("int64"))
result = a.take([0, 1], allow_fill=True, fill_value=np.nan)
tm.assert_sp_array_equal(a, result)
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index 0751c37a7f439..ffd56b9c23bc8 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -355,7 +355,7 @@ def test_astype_object_frame(self, all_data):
def test_astype_str(self, data):
result = pd.Series(data[:5]).astype(str)
- expected_dtype = pd.SparseDtype(str, str(data.fill_value))
+ expected_dtype = SparseDtype(str, str(data.fill_value))
expected = pd.Series([str(x) for x in data[:5]], dtype=expected_dtype)
self.assert_series_equal(result, expected)
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 408024e48a35a..f53378d86d7c6 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -2456,7 +2456,7 @@ def test_from_records_sequencelike(self):
# tuples is in the order of the columns
result = DataFrame.from_records(tuples)
- tm.assert_index_equal(result.columns, pd.RangeIndex(8))
+ tm.assert_index_equal(result.columns, RangeIndex(8))
# test exclude parameter & we are casting the results here (as we don't
# have dtype info to recover)
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py
index 48f87664d5141..fc59df29ef18f 100644
--- a/pandas/tests/indexes/datetimes/test_constructors.py
+++ b/pandas/tests/indexes/datetimes/test_constructors.py
@@ -53,7 +53,7 @@ def test_shallow_copy_inherits_array_freq(self, index):
def test_categorical_preserves_tz(self):
# GH#18664 retain tz when going DTI-->Categorical-->DTI
# TODO: parametrize over DatetimeIndex/DatetimeArray
- # once CategoricalIndex(DTA) works
+ # once pd.CategoricalIndex(DTA) works
dti = DatetimeIndex(
[pd.NaT, "2015-01-01", "1999-04-06 15:14:13", "2015-01-01"], tz="US/Eastern"
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index e64cadf7a8069..76f2738948872 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -6,7 +6,7 @@
from pandas._libs.tslibs import Timestamp
import pandas as pd
-from pandas import Float64Index, Index, Int64Index, Series, UInt64Index
+from pandas import Float64Index, Index, Int64Index, RangeIndex, Series, UInt64Index
import pandas._testing as tm
from pandas.tests.indexes.common import Base
@@ -171,10 +171,10 @@ def test_constructor(self):
@pytest.mark.parametrize(
"index, dtype",
[
- (pd.Int64Index, "float64"),
- (pd.UInt64Index, "categorical"),
- (pd.Float64Index, "datetime64"),
- (pd.RangeIndex, "float64"),
+ (Int64Index, "float64"),
+ (UInt64Index, "categorical"),
+ (Float64Index, "datetime64"),
+ (RangeIndex, "float64"),
],
)
def test_invalid_dtype(self, index, dtype):
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index 567d37f318fd1..9b9ece68b887e 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -445,11 +445,11 @@ def test_loc_slice(self):
def test_loc_and_at_with_categorical_index(self):
# GH 20629
- s = Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
+ s = Series([1, 2, 3], index=CategoricalIndex(["A", "B", "C"]))
assert s.loc["A"] == 1
assert s.at["A"] == 1
df = DataFrame(
- [[1, 2], [3, 4], [5, 6]], index=pd.CategoricalIndex(["A", "B", "C"])
+ [[1, 2], [3, 4], [5, 6]], index=CategoricalIndex(["A", "B", "C"])
)
assert df.loc["B", 1] == 4
assert df.at["B", 1] == 4
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index 1c9c514b20f46..26190edaa4960 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -38,6 +38,6 @@ def test_read_xlrd_book(read_ext, frame):
# TODO: test for openpyxl as well
def test_excel_table_sheet_by_index(datapath, read_ext):
path = datapath("io", "data", "excel", f"test1{read_ext}")
- with pd.ExcelFile(path) as excel:
+ with ExcelFile(path) as excel:
with pytest.raises(xlrd.XLRDError):
pd.read_excel(excel, sheet_name="asdf")
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 1e84ba1dbffd9..8c2297699807d 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -55,7 +55,7 @@ def test_ops(self, opname, obj):
if not isinstance(obj, PeriodIndex):
expected = getattr(obj.values, opname)()
else:
- expected = pd.Period(ordinal=getattr(obj.asi8, opname)(), freq=obj.freq)
+ expected = Period(ordinal=getattr(obj.asi8, opname)(), freq=obj.freq)
if getattr(obj, "tz", None) is not None:
# We need to de-localize before comparing to the numpy-produced result
@@ -470,19 +470,19 @@ def test_numpy_minmax_datetime64(self):
def test_minmax_period(self):
# monotonic
- idx1 = pd.PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D")
+ idx1 = PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D")
assert not idx1.is_monotonic
assert idx1[1:].is_monotonic
# non-monotonic
- idx2 = pd.PeriodIndex(
+ idx2 = PeriodIndex(
["2011-01-01", NaT, "2011-01-03", "2011-01-02", NaT], freq="D"
)
assert not idx2.is_monotonic
for idx in [idx1, idx2]:
- assert idx.min() == pd.Period("2011-01-01", freq="D")
- assert idx.max() == pd.Period("2011-01-03", freq="D")
+ assert idx.min() == Period("2011-01-01", freq="D")
+ assert idx.max() == Period("2011-01-03", freq="D")
assert idx1.argmin() == 1
assert idx2.argmin() == 0
assert idx1.argmax() == 3
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index d3d33d6fe847e..5d75c22c8b795 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -1285,7 +1285,7 @@ def test_resample_timegrouper():
expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
- result = df.groupby(pd.Grouper(freq="M", key="A")).count()
+ result = df.groupby(Grouper(freq="M", key="A")).count()
tm.assert_frame_equal(result, expected)
df = DataFrame(dict(A=dates, B=np.arange(len(dates)), C=np.arange(len(dates))))
@@ -1299,7 +1299,7 @@ def test_resample_timegrouper():
expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
- result = df.groupby(pd.Grouper(freq="M", key="A")).count()
+ result = df.groupby(Grouper(freq="M", key="A")).count()
tm.assert_frame_equal(result, expected)
@@ -1319,8 +1319,8 @@ def test_resample_nunique():
}
)
r = df.resample("D")
- g = df.groupby(pd.Grouper(freq="D"))
- expected = df.groupby(pd.Grouper(freq="D")).ID.apply(lambda x: x.nunique())
+ g = df.groupby(Grouper(freq="D"))
+ expected = df.groupby(Grouper(freq="D")).ID.apply(lambda x: x.nunique())
assert expected.name == "ID"
for t in [r, g]:
@@ -1330,7 +1330,7 @@ def test_resample_nunique():
result = df.ID.resample("D").nunique()
tm.assert_series_equal(result, expected)
- result = df.ID.groupby(pd.Grouper(freq="D")).nunique()
+ result = df.ID.groupby(Grouper(freq="D")).nunique()
tm.assert_series_equal(result, expected)
@@ -1443,7 +1443,7 @@ def test_groupby_with_dst_time_change():
).tz_convert("America/Chicago")
df = DataFrame([1, 2], index=index)
- result = df.groupby(pd.Grouper(freq="1d")).last()
+ result = df.groupby(Grouper(freq="1d")).last()
expected_index_values = pd.date_range(
"2016-11-02", "2016-11-24", freq="d", tz="America/Chicago"
)
@@ -1587,7 +1587,7 @@ def test_downsample_dst_at_midnight():
index = index.tz_localize("UTC").tz_convert("America/Havana")
data = list(range(len(index)))
dataframe = DataFrame(data, index=index)
- result = dataframe.groupby(pd.Grouper(freq="1D")).mean()
+ result = dataframe.groupby(Grouper(freq="1D")).mean()
dti = date_range("2018-11-03", periods=3).tz_localize(
"America/Havana", ambiguous=True
@@ -1709,9 +1709,9 @@ def test_resample_equivalent_offsets(n1, freq1, n2, freq2, k):
],
)
def test_get_timestamp_range_edges(first, last, freq, exp_first, exp_last):
- first = pd.Period(first)
+ first = Period(first)
first = first.to_timestamp(first.freq)
- last = pd.Period(last)
+ last = Period(last)
last = last.to_timestamp(last.freq)
exp_first = Timestamp(exp_first, freq=freq)
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index 8bdaad285e3f6..79fc6bae1a9eb 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -845,11 +845,11 @@ def test_resample_with_offset(self, start, end, start_freq, end_freq, offset):
],
)
def test_get_period_range_edges(self, first, last, freq, exp_first, exp_last):
- first = pd.Period(first)
- last = pd.Period(last)
+ first = Period(first)
+ last = Period(last)
- exp_first = pd.Period(exp_first, freq=freq)
- exp_last = pd.Period(exp_last, freq=freq)
+ exp_first = Period(exp_first, freq=freq)
+ exp_last = Period(exp_last, freq=freq)
freq = pd.tseries.frequencies.to_offset(freq)
result = _get_period_range_edges(first, last, freq)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index e08876226cbc8..d774417e1851c 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -411,16 +411,14 @@ def test_pivot_no_values(self):
},
index=idx,
)
- res = df.pivot_table(
- index=df.index.month, columns=pd.Grouper(key="dt", freq="M")
- )
+ res = df.pivot_table(index=df.index.month, columns=Grouper(key="dt", freq="M"))
exp_columns = MultiIndex.from_tuples([("A", pd.Timestamp("2011-01-31"))])
exp_columns.names = [None, "dt"]
exp = DataFrame([3.25, 2.0], index=[1, 2], columns=exp_columns)
tm.assert_frame_equal(res, exp)
res = df.pivot_table(
- index=pd.Grouper(freq="A"), columns=pd.Grouper(key="dt", freq="M")
+ index=Grouper(freq="A"), columns=Grouper(key="dt", freq="M")
)
exp = DataFrame(
[3], index=pd.DatetimeIndex(["2011-12-31"], freq="A"), columns=exp_columns
| Sometimes e.g. Series and pd.Series are used
in the same test file. This fixes some of these
cases, generally by using the explicitly
imported class.
- [ ] closes #xxxx
- [ ] 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/37838 | 2020-11-14T17:52:35Z | 2020-11-14T19:42:33Z | 2020-11-14T19:42:33Z | 2020-11-14T19:42:33Z |
CLN: remove unnecessary close calls and add a few necessary ones | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 425b1da33dbb9..c519baa4c21da 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -316,33 +316,36 @@ def read_excel(
"an ExcelFile - ExcelFile already has the engine set"
)
- data = io.parse(
- sheet_name=sheet_name,
- header=header,
- names=names,
- index_col=index_col,
- usecols=usecols,
- squeeze=squeeze,
- dtype=dtype,
- converters=converters,
- true_values=true_values,
- false_values=false_values,
- skiprows=skiprows,
- nrows=nrows,
- na_values=na_values,
- keep_default_na=keep_default_na,
- na_filter=na_filter,
- verbose=verbose,
- parse_dates=parse_dates,
- date_parser=date_parser,
- thousands=thousands,
- comment=comment,
- skipfooter=skipfooter,
- convert_float=convert_float,
- mangle_dupe_cols=mangle_dupe_cols,
- )
- if should_close:
- io.close()
+ try:
+ data = io.parse(
+ sheet_name=sheet_name,
+ header=header,
+ names=names,
+ index_col=index_col,
+ usecols=usecols,
+ squeeze=squeeze,
+ dtype=dtype,
+ converters=converters,
+ true_values=true_values,
+ false_values=false_values,
+ skiprows=skiprows,
+ nrows=nrows,
+ na_values=na_values,
+ keep_default_na=keep_default_na,
+ na_filter=na_filter,
+ verbose=verbose,
+ parse_dates=parse_dates,
+ date_parser=date_parser,
+ thousands=thousands,
+ comment=comment,
+ skipfooter=skipfooter,
+ convert_float=convert_float,
+ mangle_dupe_cols=mangle_dupe_cols,
+ )
+ finally:
+ # make sure to close opened file handles
+ if should_close:
+ io.close()
return data
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index c6179f5c034c7..fe471c6f6f9ac 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -818,6 +818,7 @@ def write(
f"Max sheet size is: {self.max_rows}, {self.max_cols}"
)
+ formatted_cells = self.get_formatted_cells()
if isinstance(writer, ExcelWriter):
need_save = False
else:
@@ -829,13 +830,15 @@ def write(
)
need_save = True
- formatted_cells = self.get_formatted_cells()
- writer.write_cells(
- formatted_cells,
- sheet_name,
- startrow=startrow,
- startcol=startcol,
- freeze_panes=freeze_panes,
- )
- if need_save:
- writer.save()
+ try:
+ writer.write_cells(
+ formatted_cells,
+ sheet_name,
+ startrow=startrow,
+ startcol=startcol,
+ freeze_panes=freeze_panes,
+ )
+ finally:
+ # make sure to close opened file handles
+ if need_save:
+ writer.close()
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index f30007f6ed907..1f62b6a8096a8 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -631,6 +631,7 @@ def _preprocess_data(self, data):
"""
if hasattr(data, "read") and (not self.chunksize or not self.nrows):
data = data.read()
+ self.close()
if not hasattr(data, "read") and (self.chunksize or self.nrows):
data = StringIO(data)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index ad5385cd659ef..8d9787a9c8c9e 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -2066,6 +2066,7 @@ def read(self, nrows=None):
return index, columns, col_dict
else:
+ self.close()
raise
# Done with first read, next time raise StopIteration
@@ -2449,6 +2450,7 @@ def read(self, rows=None):
if self._first_chunk:
content = []
else:
+ self.close()
raise
# done with first read, next time raise StopIteration
diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py
index e9c1bf26f6675..7c2b801ee0ea8 100644
--- a/pandas/io/sas/sas7bdat.py
+++ b/pandas/io/sas/sas7bdat.py
@@ -203,7 +203,6 @@ def _get_properties(self):
self._path_or_buf.seek(0)
self._cached_page = self._path_or_buf.read(288)
if self._cached_page[0 : len(const.magic)] != const.magic:
- self.close()
raise ValueError("magic number mismatch (not a SAS file?)")
# Get alignment information
@@ -279,7 +278,6 @@ def _get_properties(self):
buf = self._path_or_buf.read(self.header_length - 288)
self._cached_page += buf
if len(self._cached_page) != self.header_length:
- self.close()
raise ValueError("The SAS7BDAT file appears to be truncated.")
self._page_length = self._read_int(
@@ -333,6 +331,7 @@ def _get_properties(self):
def __next__(self):
da = self.read(nrows=self.chunksize or 1)
if da is None:
+ self.close()
raise StopIteration
return da
@@ -377,7 +376,6 @@ def _parse_metadata(self):
if len(self._cached_page) <= 0:
break
if len(self._cached_page) != self._page_length:
- self.close()
raise ValueError("Failed to read a meta data page from the SAS file.")
done = self._process_page_meta()
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py
index 2f5de16a7ad6c..2ecfbed8cc83f 100644
--- a/pandas/io/sas/sas_xport.py
+++ b/pandas/io/sas/sas_xport.py
@@ -276,14 +276,12 @@ def _read_header(self):
# read file header
line1 = self._get_row()
if line1 != _correct_line1:
- self.close()
raise ValueError("Header record is not an XPORT file.")
line2 = self._get_row()
fif = [["prefix", 24], ["version", 8], ["OS", 8], ["_", 24], ["created", 16]]
file_info = _split_line(line2, fif)
if file_info["prefix"] != "SAS SAS SASLIB":
- self.close()
raise ValueError("Header record has invalid prefix.")
file_info["created"] = _parse_date(file_info["created"])
self.file_info = file_info
@@ -297,7 +295,6 @@ def _read_header(self):
headflag1 = header1.startswith(_correct_header1)
headflag2 = header2 == _correct_header2
if not (headflag1 and headflag2):
- self.close()
raise ValueError("Member header not found")
# usually 140, could be 135
fieldnamelength = int(header1[-5:-2])
@@ -346,7 +343,6 @@ def _read_header(self):
field["ntype"] = types[field["ntype"]]
fl = field["field_length"]
if field["ntype"] == "numeric" and ((fl < 2) or (fl > 8)):
- self.close()
msg = f"Floating field width {fl} is not between 2 and 8."
raise TypeError(msg)
@@ -361,7 +357,6 @@ def _read_header(self):
header = self._get_row()
if not header == _correct_obs_header:
- self.close()
raise ValueError("Observation header not found.")
self.fields = fields
diff --git a/pandas/tests/io/parser/test_compression.py b/pandas/tests/io/parser/test_compression.py
index 5680669f75aa3..6e957313d8de8 100644
--- a/pandas/tests/io/parser/test_compression.py
+++ b/pandas/tests/io/parser/test_compression.py
@@ -23,7 +23,7 @@ def parser_and_data(all_parsers, csv1):
with open(csv1, "rb") as f:
data = f.read()
- expected = parser.read_csv(csv1)
+ expected = parser.read_csv(csv1)
return parser, data, expected
| - [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Follow up to #37639. Close file handles as early as possible.
Remove `close` calls that are already within a try-except/finally block that closes the file handles.
Add `close` call for `read_json` when we read the entire content in one go.
Add close call in `read_csv` when reaching the end of the iterator.
Put `to/read_excel` in a try-finally block to make sure that file handles are closed even in case of an exception. | https://api.github.com/repos/pandas-dev/pandas/pulls/37837 | 2020-11-14T17:50:45Z | 2020-11-15T17:07:59Z | 2020-11-15T17:07:59Z | 2020-11-15T17:29:32Z |
COMPAT: should an empty string match a format (or just be NaT) | diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 10bda16655586..278a315a479bd 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2443,3 +2443,34 @@ def test_na_to_datetime(nulls_fixture, klass):
result = pd.to_datetime(klass([nulls_fixture]))
assert result[0] is pd.NaT
+
+
+def test_empty_string_datetime_coerce__format():
+ # GH13044
+ td = Series(["03/24/2016", "03/25/2016", ""])
+ format = "%m/%d/%Y"
+
+ # coerce empty string to pd.NaT
+ result = pd.to_datetime(td, format=format, errors="coerce")
+ expected = Series(["2016-03-24", "2016-03-25", pd.NaT], dtype="datetime64[ns]")
+ tm.assert_series_equal(expected, result)
+
+ # raise an exception in case a format is given
+ with pytest.raises(ValueError, match="does not match format"):
+ result = pd.to_datetime(td, format=format, errors="raise")
+
+ # don't raise an expection in case no format is given
+ result = pd.to_datetime(td, errors="raise")
+ tm.assert_series_equal(result, expected)
+
+
+def test_empty_string_datetime_coerce__unit():
+ # GH13044
+ # coerce empty string to pd.NaT
+ result = pd.to_datetime([1, ""], unit="s", errors="coerce")
+ expected = DatetimeIndex(["1970-01-01 00:00:01", "NaT"], dtype="datetime64[ns]")
+ tm.assert_index_equal(expected, result)
+
+ # verify that no exception is raised even when errors='raise' is set
+ result = pd.to_datetime([1, ""], unit="s", errors="raise")
+ tm.assert_index_equal(expected, result)
| - [x] closes #13044
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry (not applicable)
| https://api.github.com/repos/pandas-dev/pandas/pulls/37835 | 2020-11-14T17:39:54Z | 2020-11-19T18:58:15Z | 2020-11-19T18:58:15Z | 2020-11-19T18:58:21Z |
BUG: Parse missing values using read_json with dtype=False to NaN instead of None (GH28501) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index cea42cbffa906..41964f7fd3997 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -653,6 +653,7 @@ I/O
- Bug in :func:`read_html` was raising a ``TypeError`` when supplying a ``pathlib.Path`` argument to the ``io`` parameter (:issue:`37705`)
- :meth:`to_excel` and :meth:`to_markdown` support writing to fsspec URLs such as S3 and Google Cloud Storage (:issue:`33987`)
- Bug in :meth:`read_fw` was not skipping blank lines (even with ``skip_blank_lines=True``) (:issue:`37758`)
+- Parse missing values using :func:`read_json` with ``dtype=False`` to ``NaN`` instead of ``None`` (:issue:`28501`)
- :meth:`read_fwf` was inferring compression with ``compression=None`` which was not consistent with the other :meth:``read_*`` functions (:issue:`37909`)
Period
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 8129d58d5cb34..e1feb1aa3fada 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -20,7 +20,7 @@
from pandas.core.dtypes.common import ensure_str, is_period_dtype
-from pandas import DataFrame, MultiIndex, Series, isna, to_datetime
+from pandas import DataFrame, MultiIndex, Series, isna, notna, to_datetime
from pandas.core import generic
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.generic import NDFrame
@@ -858,7 +858,10 @@ def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):
# don't try to coerce, unless a force conversion
if use_dtypes:
if not self.dtype:
- return data, False
+ if all(notna(data)):
+ return data, False
+ return data.fillna(np.nan), True
+
elif self.dtype is True:
pass
else:
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 3e5f9d481ce48..fdf2caa804def 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -345,10 +345,16 @@ def test_frame_from_json_missing_data(self, orient, convert_axes, numpy, dtype):
convert_axes=convert_axes,
dtype=dtype,
)
- if not dtype: # TODO: Special case for object data; maybe a bug?
- assert result.iloc[0, 2] is None
- else:
- assert np.isnan(result.iloc[0, 2])
+ assert np.isnan(result.iloc[0, 2])
+
+ @pytest.mark.parametrize("dtype", [True, False])
+ def test_frame_read_json_dtype_missing_value(self, orient, dtype):
+ # GH28501 Parse missing values using read_json with dtype=False
+ # to NaN instead of None
+ result = read_json("[null]", dtype=dtype)
+ expected = DataFrame([np.nan])
+
+ tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("inf", [np.inf, np.NINF])
@pytest.mark.parametrize("dtype", [True, False])
|
- [x] closes #28501
- [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/37834 | 2020-11-14T16:52:13Z | 2020-11-20T02:51:30Z | 2020-11-20T02:51:29Z | 2020-11-20T14:49:39Z |
Return view for xs when droplevel=False with regular Index | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 49e992b14293e..bcb46ad6d1873 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3751,7 +3751,7 @@ class animal locomotion
dtype=new_values.dtype,
)
elif is_scalar(loc):
- result = self.iloc[:, [loc]]
+ result = self.iloc[:, slice(loc, loc + 1)]
elif axis == 1:
result = self.iloc[:, loc]
else:
diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py
index a90141e9fad60..3be3ce15622b4 100644
--- a/pandas/tests/frame/indexing/test_xs.py
+++ b/pandas/tests/frame/indexing/test_xs.py
@@ -319,3 +319,11 @@ def test_xs_droplevel_false(self):
result = df.xs("a", axis=1, drop_level=False)
expected = DataFrame({"a": [1]})
tm.assert_frame_equal(result, expected)
+
+ def test_xs_droplevel_false_view(self):
+ # GH#37832
+ df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
+ result = df.xs("a", axis=1, drop_level=False)
+ df.values[0, 0] = 2
+ expected = DataFrame({"a": [2]})
+ tm.assert_frame_equal(result, expected)
| - [x] xref #37776
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Is there a better way to test, if the object is a view?
cc @jbrockmendel
| https://api.github.com/repos/pandas-dev/pandas/pulls/37832 | 2020-11-14T13:07:24Z | 2020-11-15T17:26:35Z | 2020-11-15T17:26:35Z | 2021-12-10T09:23:44Z |
BUG: MultiIndex.drop does not raise if labels are partially found | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 727b5ec92bdc4..f3fc91b331359 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -617,6 +617,7 @@ Indexing
- Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty :class:`DataFrame` with ``tolerance`` not None or ``method="nearest"`` (:issue:`27315`)
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
+- Bug in :meth:`MultiIndex.drop` does not raise if labels are partially found (:issue:`37820`)
- Bug in :meth:`DataFrame.loc` did not raise ``KeyError`` when missing combination was given with ``slice(None)`` for remaining levels (:issue:`19556`)
Missing
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 9c80236129155..6342e6c793608 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2084,7 +2084,7 @@ def drop(self, codes, level=None, errors="raise"):
Parameters
----------
codes : array-like
- Must be a list of tuples
+ Must be a list of tuples when level is not specified
level : int or level name, default None
errors : str, default 'raise'
@@ -2139,10 +2139,13 @@ def _drop_from_level(self, codes, level, errors="raise"):
# are not nan and equal -1, this means they are missing in the index
nan_codes = isna(codes)
values[(np.equal(nan_codes, False)) & (values == -1)] = -2
+ if index.shape[0] == self.shape[0]:
+ values[np.equal(nan_codes, True)] = -2
+ not_found = codes[values == -2]
+ if len(not_found) != 0 and errors != "ignore":
+ raise KeyError(f"labels {not_found} not found in level")
mask = ~algos.isin(self.codes[i], values)
- if mask.all() and errors != "ignore":
- raise KeyError(f"labels {codes} not found in level")
return self[mask]
diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py
index 06019ed0a8b14..c39954b22b0f2 100644
--- a/pandas/tests/indexes/multi/test_drop.py
+++ b/pandas/tests/indexes/multi/test_drop.py
@@ -147,3 +147,24 @@ def test_drop_with_nan_in_index(nulls_fixture):
msg = r"labels \[Timestamp\('2001-01-01 00:00:00'\)\] not found in level"
with pytest.raises(KeyError, match=msg):
mi.drop(pd.Timestamp("2001"), level="date")
+
+
+def test_single_level_drop_partially_missing_elements():
+ # GH 37820
+
+ mi = MultiIndex.from_tuples([(1, 2), (2, 2), (3, 2)])
+ msg = r"labels \[4\] not found in level"
+ with pytest.raises(KeyError, match=msg):
+ mi.drop(4, level=0)
+ with pytest.raises(KeyError, match=msg):
+ mi.drop([1, 4], level=0)
+ msg = r"labels \[nan\] not found in level"
+ with pytest.raises(KeyError, match=msg):
+ mi.drop([np.nan], level=0)
+ with pytest.raises(KeyError, match=msg):
+ mi.drop([np.nan, 1, 2, 3], level=0)
+
+ mi = MultiIndex.from_tuples([(np.nan, 1), (1, 2)])
+ msg = r"labels \['a'\] not found in level"
+ with pytest.raises(KeyError, match=msg):
+ mi.drop([np.nan, 1, "a"], level=0)
| - [x] closes #37820
- [x] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37830 | 2020-11-14T09:42:49Z | 2020-11-26T22:38:05Z | 2020-11-26T22:38:05Z | 2020-11-27T01:02:10Z |
Backport PR #37801 on branch 1.1.x: REGR: SeriesGroupBy where index has a tuple name fails | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index 3b1f64e730830..2a598c489e809 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
+- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 18a201674db65..277aa1d095350 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -889,7 +889,7 @@ def __getitem__(self, key):
return result
- except KeyError:
+ except (KeyError, TypeError):
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
# We still have the corner case where a tuple is a key
# in the first level of our MultiIndex
@@ -953,7 +953,7 @@ def _get_values_tuple(self, key):
return result
if not isinstance(self.index, MultiIndex):
- raise ValueError("key of type tuple not found and not a MultiIndex")
+ raise KeyError("key of type tuple not found and not a MultiIndex")
# If key is contained, would have returned by now
indexer, new_index = self.index.get_loc_level(key)
@@ -1009,7 +1009,7 @@ def __setitem__(self, key, value):
except TypeError as err:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex):
- raise ValueError(
+ raise KeyError(
"key of type tuple not found and not a MultiIndex"
) from err
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index bdb283ae445b1..35eab708412b8 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2055,3 +2055,13 @@ def test_groups_repr_truncates(max_seq_items, expected):
result = df.groupby(np.array(df.a)).groups.__repr__()
assert result == expected
+
+
+def test_groupby_series_with_tuple_name():
+ # GH 37755
+ ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
+ ser.index.name = ("b", "b")
+ result = ser.groupby(level=0).last()
+ expected = Series([2, 4], index=[1, 2], name=("a", "a"))
+ expected.index.name = ("b", "b")
+ tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index fbdac2bb2d8e8..3b66939d9ddd2 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -387,9 +387,9 @@ def test_2d_to_1d_assignment_raises():
def test_basic_getitem_setitem_corner(datetime_series):
# invalid tuples, e.g. td.ts[:, None] vs. td.ts[:, 2]
msg = "key of type tuple not found and not a MultiIndex"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(KeyError, match=msg):
datetime_series[:, 2]
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(KeyError, match=msg):
datetime_series[:, 2] = 2
# weird lists. [slice(0, 5)] will work but not two slices
| Backport PR #37801 | https://api.github.com/repos/pandas-dev/pandas/pulls/37829 | 2020-11-14T09:33:03Z | 2020-11-14T10:30:20Z | 2020-11-14T10:30:20Z | 2020-11-14T10:30:29Z |
CLN: File handling for PyArrow parquet | diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index c76e18ae353a0..1f90da2f57579 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -2,7 +2,7 @@
import io
import os
-from typing import Any, AnyStr, Dict, List, Optional
+from typing import Any, AnyStr, Dict, List, Optional, Tuple
from warnings import catch_warnings
from pandas._typing import FilePathOrBuffer, StorageOptions
@@ -11,7 +11,7 @@
from pandas import DataFrame, get_option
-from pandas.io.common import get_handle, is_fsspec_url, stringify_path
+from pandas.io.common import IOHandles, get_handle, is_fsspec_url, stringify_path
def get_engine(engine: str) -> "BaseImpl":
@@ -48,6 +48,40 @@ def get_engine(engine: str) -> "BaseImpl":
raise ValueError("engine must be one of 'pyarrow', 'fastparquet'")
+def _get_path_or_handle(
+ path: FilePathOrBuffer,
+ fs: Any,
+ storage_options: StorageOptions = None,
+ mode: str = "rb",
+ is_dir: bool = False,
+) -> Tuple[FilePathOrBuffer, Optional[IOHandles], Any]:
+ """File handling for PyArrow."""
+ path_or_handle = stringify_path(path)
+ if is_fsspec_url(path_or_handle) and fs is None:
+ fsspec = import_optional_dependency("fsspec")
+
+ fs, path_or_handle = fsspec.core.url_to_fs(
+ path_or_handle, **(storage_options or {})
+ )
+ elif storage_options:
+ raise ValueError("storage_options passed with buffer or non-fsspec filepath")
+
+ handles = None
+ if (
+ not fs
+ and not is_dir
+ and isinstance(path_or_handle, str)
+ and not os.path.isdir(path_or_handle)
+ ):
+ # use get_handle only when we are very certain that it is not a directory
+ # fsspec resources can also point to directories
+ # this branch is used for example when reading from non-fsspec URLs
+ handles = get_handle(path_or_handle, mode, is_text=False)
+ fs = None
+ path_or_handle = handles.handle
+ return path_or_handle, handles, fs
+
+
class BaseImpl:
@staticmethod
def validate_dataframe(df: DataFrame):
@@ -103,64 +137,50 @@ def write(
table = self.api.Table.from_pandas(df, **from_pandas_kwargs)
- path = stringify_path(path)
- # get_handle could be used here (for write_table, not for write_to_dataset)
- # but it would complicate the code.
- if is_fsspec_url(path) and "filesystem" not in kwargs:
- # make fsspec instance, which pyarrow will use to open paths
- fsspec = import_optional_dependency("fsspec")
-
- fs, path = fsspec.core.url_to_fs(path, **(storage_options or {}))
- kwargs["filesystem"] = fs
-
- elif storage_options:
- raise ValueError(
- "storage_options passed with file object or non-fsspec file path"
- )
-
- if partition_cols is not None:
- # writes to multiple files under the given path
- self.api.parquet.write_to_dataset(
- table,
- path,
- compression=compression,
- partition_cols=partition_cols,
- **kwargs,
- )
- else:
- # write to single output file
- self.api.parquet.write_table(table, path, compression=compression, **kwargs)
+ path_or_handle, handles, kwargs["filesystem"] = _get_path_or_handle(
+ path,
+ kwargs.pop("filesystem", None),
+ storage_options=storage_options,
+ mode="wb",
+ is_dir=partition_cols is not None,
+ )
+ try:
+ if partition_cols is not None:
+ # writes to multiple files under the given path
+ self.api.parquet.write_to_dataset(
+ table,
+ path_or_handle,
+ compression=compression,
+ partition_cols=partition_cols,
+ **kwargs,
+ )
+ else:
+ # write to single output file
+ self.api.parquet.write_table(
+ table, path_or_handle, compression=compression, **kwargs
+ )
+ finally:
+ if handles is not None:
+ handles.close()
def read(
self, path, columns=None, storage_options: StorageOptions = None, **kwargs
):
- path = stringify_path(path)
- handles = None
- fs = kwargs.pop("filesystem", None)
- if is_fsspec_url(path) and fs is None:
- fsspec = import_optional_dependency("fsspec")
-
- fs, path = fsspec.core.url_to_fs(path, **(storage_options or {}))
- elif storage_options:
- raise ValueError(
- "storage_options passed with buffer or non-fsspec filepath"
- )
- if not fs and isinstance(path, str) and not os.path.isdir(path):
- # use get_handle only when we are very certain that it is not a directory
- # fsspec resources can also point to directories
- # this branch is used for example when reading from non-fsspec URLs
- handles = get_handle(path, "rb", is_text=False)
- path = handles.handle
-
kwargs["use_pandas_metadata"] = True
- result = self.api.parquet.read_table(
- path, columns=columns, filesystem=fs, **kwargs
- ).to_pandas()
- if handles is not None:
- handles.close()
-
- return result
+ path_or_handle, handles, kwargs["filesystem"] = _get_path_or_handle(
+ path,
+ kwargs.pop("filesystem", None),
+ storage_options=storage_options,
+ mode="rb",
+ )
+ try:
+ return self.api.parquet.read_table(
+ path_or_handle, columns=columns, **kwargs
+ ).to_pandas()
+ finally:
+ if handles is not None:
+ handles.close()
class FastParquetImpl(BaseImpl):
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 123e115cd2f2a..e5fffb0e3a3e8 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -691,6 +691,7 @@ def test_partition_cols_supported(self, pa, df_full):
dataset = pq.ParquetDataset(path, validate_schema=False)
assert len(dataset.partitions.partition_names) == 2
assert dataset.partitions.partition_names == set(partition_cols)
+ assert read_parquet(path).shape == df.shape
def test_partition_cols_string(self, pa, df_full):
# GH #27117
@@ -704,6 +705,7 @@ def test_partition_cols_string(self, pa, df_full):
dataset = pq.ParquetDataset(path, validate_schema=False)
assert len(dataset.partitions.partition_names) == 1
assert dataset.partitions.partition_names == set(partition_cols_list)
+ assert read_parquet(path).shape == df.shape
@pytest.mark.parametrize("path_type", [str, pathlib.Path])
def test_partition_cols_pathlib(self, pa, df_compat, path_type):
@@ -716,6 +718,7 @@ def test_partition_cols_pathlib(self, pa, df_compat, path_type):
with tm.ensure_clean_dir() as path_str:
path = path_type(path_str)
df.to_parquet(path, partition_cols=partition_cols_list)
+ assert read_parquet(path).shape == df.shape
def test_empty_dataframe(self, pa):
# GH #27339
| - [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
De-duplicate file handling of PyArrows' parquet. | https://api.github.com/repos/pandas-dev/pandas/pulls/37828 | 2020-11-14T05:35:26Z | 2020-11-18T13:49:56Z | 2020-11-18T13:49:56Z | 2020-11-19T04:12:57Z |
BUG: DataFrame reductions inconsistent with Series counterparts | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 54d8ba1edea39..d848413d7193c 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -284,6 +284,63 @@ of columns could result in a larger :class:`Series` result. See (:issue:`37799`)
In [6]: df[["B", "C"]].all(bool_only=True)
+Other :class:`DataFrame` reductions with ``numeric_only=None`` will also avoid
+this pathological behavior (:issue:`37827`):
+
+.. ipython:: python
+
+ df = pd.DataFrame({"A": [0, 1, 2], "B": ["a", "b", "c"]}, dtype=object)
+
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [3]: df.mean()
+ Out[3]: Series([], dtype: float64)
+
+ In [4]: df[["A"]].mean()
+ Out[4]:
+ A 1.0
+ dtype: float64
+
+*New behavior*:
+
+.. ipython:: python
+
+ df.mean()
+
+ df[["A"]].mean()
+
+Moreover, :class:`DataFrame` reductions with ``numeric_only=None`` will now be
+consistent with their :class:`Series` counterparts. In particular, for
+reductions where the :class:`Series` method raises ``TypeError``, the
+:class:`DataFrame` reduction will now consider that column non-numeric
+instead of casting to NumPy which may have different semantics (:issue:`36076`,
+:issue:`28949`, :issue:`21020`).
+
+.. ipython:: python
+
+ ser = pd.Series([0, 1], dtype="category", name="A")
+ df = ser.to_frame()
+
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [5]: df.any()
+ Out[5]:
+ A True
+ dtype: bool
+
+*New behavior*:
+
+.. ipython:: python
+
+ df.any()
+
+
.. _whatsnew_120.api_breaking.python:
Increased minimum version for Python
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index bae06339a1e60..4310d23e4d7f3 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8765,7 +8765,7 @@ def _get_data() -> DataFrame:
data = self._get_bool_data()
return data
- if numeric_only is not None:
+ if numeric_only is not None or axis == 0:
# For numeric_only non-None and axis non-None, we know
# which blocks to use and no try/except is needed.
# For numeric_only=None only the case with axis==0 and no object
@@ -8790,36 +8790,14 @@ def _get_data() -> DataFrame:
# GH#35865 careful to cast explicitly to object
nvs = coerce_to_dtypes(out.values, df.dtypes.iloc[np.sort(indexer)])
out[:] = np.array(nvs, dtype=object)
+ if axis == 0 and len(self) == 0 and name in ["sum", "prod"]:
+ # Even if we are object dtype, follow numpy and return
+ # float64, see test_apply_funcs_over_empty
+ out = out.astype(np.float64)
return out
assert numeric_only is None
- if not self._is_homogeneous_type or self._mgr.any_extension_types:
- # try to avoid self.values call
-
- if filter_type is None and axis == 0:
- # operate column-wise
-
- # numeric_only must be None here, as other cases caught above
-
- # this can end up with a non-reduction
- # but not always. if the types are mixed
- # with datelike then need to make sure a series
-
- # we only end up here if we have not specified
- # numeric_only and yet we have tried a
- # column-by-column reduction, where we have mixed type.
- # So let's just do what we can
- from pandas.core.apply import frame_apply
-
- opa = frame_apply(
- self, func=func, result_type="expand", ignore_failures=True
- )
- result = opa.get_result()
- if result.ndim == self.ndim:
- result = result.iloc[0].rename(None)
- return result
-
data = self
values = data.values
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 92f6bb6f1cbdd..967e218078a28 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -464,7 +464,9 @@ def _split(self) -> List["Block"]:
new_blocks.append(nb)
return new_blocks
- def split_and_operate(self, mask, f, inplace: bool) -> List["Block"]:
+ def split_and_operate(
+ self, mask, f, inplace: bool, ignore_failures: bool = False
+ ) -> List["Block"]:
"""
split the block per-column, and apply the callable f
per-column, return a new block for each. Handle
@@ -474,7 +476,8 @@ def split_and_operate(self, mask, f, inplace: bool) -> List["Block"]:
----------
mask : 2-d boolean mask
f : callable accepting (1d-mask, 1d values, indexer)
- inplace : boolean
+ inplace : bool
+ ignore_failures : bool, default False
Returns
-------
@@ -513,8 +516,16 @@ def make_a_block(nv, ref_loc):
v = new_values[i]
# need a new block
- if m.any():
- nv = f(m, v, i)
+ if m.any() or m.size == 0:
+ # Apply our function; we may ignore_failures if this is a
+ # reduction that is dropping nuisance columns GH#37827
+ try:
+ nv = f(m, v, i)
+ except TypeError:
+ if ignore_failures:
+ continue
+ else:
+ raise
else:
nv = v if inplace else v.copy()
@@ -2459,7 +2470,9 @@ def mask_func(mask, values, inplace):
values = values.reshape(1, -1)
return func(values)
- return self.split_and_operate(None, mask_func, False)
+ return self.split_and_operate(
+ None, mask_func, False, ignore_failures=ignore_failures
+ )
try:
res = func(values)
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 95cb770a11408..299f00e818105 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -12,6 +12,7 @@
from pandas import (
Categorical,
DataFrame,
+ Index,
MultiIndex,
Series,
Timestamp,
@@ -1083,10 +1084,12 @@ def test_any_all_bool_only(self):
pytest.param(np.any, {"A": Series([0, 1], dtype="m8[ns]")}, True),
pytest.param(np.all, {"A": Series([1, 2], dtype="m8[ns]")}, True),
pytest.param(np.any, {"A": Series([1, 2], dtype="m8[ns]")}, True),
- (np.all, {"A": Series([0, 1], dtype="category")}, False),
- (np.any, {"A": Series([0, 1], dtype="category")}, True),
+ # np.all on Categorical raises, so the reduction drops the
+ # column, so all is being done on an empty Series, so is True
+ (np.all, {"A": Series([0, 1], dtype="category")}, True),
+ (np.any, {"A": Series([0, 1], dtype="category")}, False),
(np.all, {"A": Series([1, 2], dtype="category")}, True),
- (np.any, {"A": Series([1, 2], dtype="category")}, True),
+ (np.any, {"A": Series([1, 2], dtype="category")}, False),
# Mix GH#21484
pytest.param(
np.all,
@@ -1308,6 +1311,114 @@ def test_frame_any_with_timedelta(self):
tm.assert_series_equal(result, expected)
+class TestNuisanceColumns:
+ @pytest.mark.parametrize("method", ["any", "all"])
+ def test_any_all_categorical_dtype_nuisance_column(self, method):
+ # GH#36076 DataFrame should match Series behavior
+ ser = Series([0, 1], dtype="category", name="A")
+ df = ser.to_frame()
+
+ # Double-check the Series behavior is to raise
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ getattr(ser, method)()
+
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ getattr(np, method)(ser)
+
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ getattr(df, method)(bool_only=False)
+
+ # With bool_only=None, operating on this column raises and is ignored,
+ # so we expect an empty result.
+ result = getattr(df, method)(bool_only=None)
+ expected = Series([], index=Index([]), dtype=bool)
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(np, method)(df, axis=0)
+ tm.assert_series_equal(result, expected)
+
+ def test_median_categorical_dtype_nuisance_column(self):
+ # GH#21020 DataFrame.median should match Series.median
+ df = DataFrame({"A": Categorical([1, 2, 2, 2, 3])})
+ ser = df["A"]
+
+ # Double-check the Series behavior is to raise
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ ser.median()
+
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ df.median(numeric_only=False)
+
+ result = df.median()
+ expected = Series([], index=Index([]), dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+ # same thing, but with an additional non-categorical column
+ df["B"] = df["A"].astype(int)
+
+ with pytest.raises(TypeError, match="does not implement reduction"):
+ df.median(numeric_only=False)
+
+ result = df.median()
+ expected = Series([2.0], index=["B"])
+ tm.assert_series_equal(result, expected)
+
+ # TODO: np.median(df, axis=0) gives np.array([2.0, 2.0]) instead
+ # of expected.values
+
+ @pytest.mark.parametrize("method", ["min", "max"])
+ def test_min_max_categorical_dtype_non_ordered_nuisance_column(self, method):
+ # GH#28949 DataFrame.min should behave like Series.min
+ cat = Categorical(["a", "b", "c", "b"], ordered=False)
+ ser = Series(cat)
+ df = ser.to_frame("A")
+
+ # Double-check the Series behavior
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(ser, method)()
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(np, method)(ser)
+
+ with pytest.raises(TypeError, match="is not ordered for operation"):
+ getattr(df, method)(numeric_only=False)
+
+ result = getattr(df, method)()
+ expected = Series([], index=Index([]), dtype=np.float64)
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(np, method)(df)
+ tm.assert_series_equal(result, expected)
+
+ # same thing, but with an additional non-categorical column
+ df["B"] = df["A"].astype(object)
+ result = getattr(df, method)()
+ if method == "min":
+ expected = Series(["a"], index=["B"])
+ else:
+ expected = Series(["c"], index=["B"])
+ tm.assert_series_equal(result, expected)
+
+ result = getattr(np, method)(df)
+ tm.assert_series_equal(result, expected)
+
+ def test_reduction_object_block_splits_nuisance_columns(self):
+ # GH#37827
+ df = DataFrame({"A": [0, 1, 2], "B": ["a", "b", "c"]}, dtype=object)
+
+ # We should only exclude "B", not "A"
+ result = df.mean()
+ expected = Series([1.0], index=["A"])
+ tm.assert_series_equal(result, expected)
+
+ # Same behavior but heterogeneous dtype
+ df["C"] = df["A"].astype(int) + 4
+
+ result = df.mean()
+ expected = Series([1.0, 5.0], index=["A", "C"])
+ tm.assert_series_equal(result, expected)
+
+
def test_sum_timedelta64_skipna_false():
# GH#17235
arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2)
@@ -1352,6 +1463,6 @@ def test_minmax_extensionarray(method, numeric_only):
df = DataFrame({"Int64": ser})
result = getattr(df, method)(numeric_only=numeric_only)
expected = Series(
- [getattr(int64_info, method)], index=pd.Index(["Int64"], dtype="object")
+ [getattr(int64_info, method)], index=Index(["Int64"], dtype="object")
)
tm.assert_series_equal(result, expected)
| - [x] closes #36076
- [x] closes #28949
- [x] closes #21020
- [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/37827 | 2020-11-14T02:58:28Z | 2020-11-14T19:38:31Z | 2020-11-14T19:38:31Z | 2020-11-14T19:40:53Z |
CLN: Old shell scripts | diff --git a/ci/check_cache.sh b/ci/check_cache.sh
deleted file mode 100755
index b83144fc45ef4..0000000000000
--- a/ci/check_cache.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-
-# currently not used
-# script to make sure that cache is clean
-# Travis CI now handles this
-
-if [ "$TRAVIS_PULL_REQUEST" == "false" ]
-then
- echo "Not a PR: checking for changes in ci/ from last 2 commits"
- git diff HEAD~2 --numstat | grep -E "ci/"
- ci_changes=$(git diff HEAD~2 --numstat | grep -E "ci/"| wc -l)
-else
- echo "PR: checking for changes in ci/ from last 2 commits"
- git fetch origin pull/${TRAVIS_PULL_REQUEST}/head:PR_HEAD
- git diff PR_HEAD~2 --numstat | grep -E "ci/"
- ci_changes=$(git diff PR_HEAD~2 --numstat | grep -E "ci/"| wc -l)
-fi
-
-CACHE_DIR="$HOME/.cache/"
-CCACHE_DIR="$HOME/.ccache/"
-
-if [ $ci_changes -ne 0 ]
-then
- echo "Files have changed in ci/ deleting all caches"
- rm -rf "$CACHE_DIR"
- rm -rf "$CCACHE_DIR"
-fi
diff --git a/release_stats.sh b/release_stats.sh
deleted file mode 100755
index 1e82447007796..0000000000000
--- a/release_stats.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-
-while [[ $# > 1 ]]
-do
-key="$1"
-
-case $key in
- --from)
- FROM="$2"
- shift # past argument
- ;;
- --to)
- TO="$2"
- shift # past argument
- ;;
- *)
- # unknown option
- ;;
-esac
-shift # past argument or value
-done
-
-if [ -z "$FROM" ]; then
- FROM=`git tag --sort v:refname | grep -v rc | tail -1`
-fi
-
-if [ -z "$TO" ]; then
- TO=""
-fi
-
-START=`git log $FROM.. --simplify-by-decoration --pretty="format:%ai %d" | tail -1 | gawk '{ print $1 }'`
-END=`git log $TO.. --simplify-by-decoration --pretty="format:%ai %d" | head -1 | gawk '{ print $1 }'`
-
-git log $FROM.. --format='%an#%s' | grep -v Merge > commits
-
-# Include a summary by contributor in release notes:
-# cat commits | gawk -F '#' '{ print "- " $1 }' | sort | uniq
-
-echo "Stats since <$FROM> [$START - $END]"
-echo ""
-
-AUTHORS=`cat commits | gawk -F '#' '{ print $1 }' | sort | uniq | wc -l`
-echo "Number of authors: $AUTHORS"
-
-TCOMMITS=`cat commits | gawk -F '#' '{ print $1 }'| wc -l`
-echo "Total commits : $TCOMMITS"
-
-# Include a summary count of commits included in the release by contributor:
-# cat commits | gawk -F '#' '{ print $1 }' | sort | uniq -c | sort -nr
-
-/bin/rm commits
diff --git a/test.sh b/test.sh
deleted file mode 100755
index 1255a39816f78..0000000000000
--- a/test.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-command -v coverage >/dev/null && coverage erase
-command -v python-coverage >/dev/null && python-coverage erase
-pytest pandas --cov=pandas -r sxX --strict
diff --git a/test_rebuild.sh b/test_rebuild.sh
deleted file mode 100755
index 65aa1098811a1..0000000000000
--- a/test_rebuild.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/sh
-
-python setup.py clean
-python setup.py build_ext --inplace
-coverage erase
-pytest pandas --cov=pandas
| The scripts were not documented and don't seem to be used anywhere. | https://api.github.com/repos/pandas-dev/pandas/pulls/37825 | 2020-11-14T01:57:17Z | 2020-11-14T03:24:01Z | 2020-11-14T03:24:01Z | 2020-11-14T03:24:33Z |
CLN: avoid incorrect usages of values_for_argsort | diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index 3103c27b35d74..4d09a97b18eed 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -231,10 +231,7 @@ def __getitem__(self, key):
# ---------------------------------------------------------------------
def _get_engine_target(self) -> np.ndarray:
- # NB: _values_for_argsort happens to match the desired engine targets
- # for all of our existing EA-backed indexes, but in general
- # cannot be relied upon to exist.
- return self._data._values_for_argsort()
+ return np.asarray(self._data)
def repeat(self, repeats, axis=None):
nv.validate_repeat(tuple(), dict(axis=axis))
@@ -306,6 +303,9 @@ class NDArrayBackedExtensionIndex(ExtensionIndex):
_data: NDArrayBackedExtensionArray
+ def _get_engine_target(self) -> np.ndarray:
+ return self._data._ndarray
+
def delete(self, loc):
"""
Make new Index with passed location(-s) deleted
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 8efba87b14ce5..205af5354d333 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -227,7 +227,7 @@ def is_na(self) -> bool:
return isna_all(values_flat)
- def get_reindexed_values(self, empty_dtype, upcasted_na):
+ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na):
if upcasted_na is None:
# No upcasting is necessary
fill_value = self.block.fill_value
@@ -248,9 +248,8 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
empty_dtype
):
if self.block is None:
- array = empty_dtype.construct_array_type()
# TODO(EA2D): special case unneeded with 2D EAs
- return array(
+ return DatetimeArray(
np.full(self.shape[1], fill_value.value), dtype=empty_dtype
)
elif getattr(self.block, "is_categorical", False):
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index dd45a00155721..918a894a27916 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -6,7 +6,7 @@
import datetime
from functools import partial
import string
-from typing import TYPE_CHECKING, Optional, Tuple
+from typing import TYPE_CHECKING, Optional, Tuple, cast
import warnings
import numpy as np
@@ -50,6 +50,7 @@
if TYPE_CHECKING:
from pandas import DataFrame
+ from pandas.core.arrays import DatetimeArray
@Substitution("\nleft : DataFrame")
@@ -1947,8 +1948,8 @@ def _factorize_keys(
if is_datetime64tz_dtype(lk.dtype) and is_datetime64tz_dtype(rk.dtype):
# Extract the ndarray (UTC-localized) values
# Note: we dont need the dtypes to match, as these can still be compared
- lk, _ = lk._values_for_factorize()
- rk, _ = rk._values_for_factorize()
+ lk = cast("DatetimeArray", lk)._ndarray
+ rk = cast("DatetimeArray", rk)._ndarray
elif (
is_categorical_dtype(lk.dtype)
| https://api.github.com/repos/pandas-dev/pandas/pulls/37824 | 2020-11-13T22:55:56Z | 2020-11-14T03:34:14Z | 2020-11-14T03:34:14Z | 2020-11-14T03:41:00Z | |
BUG: Allow custom error values in parse_dates argument of read_sql like functions (GH35185) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 70b07e08cf760..7c2a1199bdf0e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -220,6 +220,7 @@ I/O
- Bug in :func:`read_csv` raising ``IndexError`` with multiple header columns and ``index_col`` specified when file has no data rows (:issue:`38292`)
- Bug in :func:`read_csv` not accepting ``usecols`` with different length than ``names`` for ``engine="python"`` (:issue:`16469`)
- Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`)
+- Allow custom error values for parse_dates argument of :func:`read_sql`, :func:`read_sql_query` and :func:`read_sql_table` (:issue:`35185`)
-
Period
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 5678133d5a706..b7efb4a8d6947 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -79,7 +79,12 @@ def _process_parse_dates_argument(parse_dates):
def _handle_date_column(col, utc=None, format=None):
if isinstance(format, dict):
- return to_datetime(col, errors="ignore", **format)
+ # GH35185 Allow custom error values in parse_dates argument of
+ # read_sql like functions.
+ # Format can take on custom to_datetime argument values such as
+ # {"errors": "coerce"} or {"dayfirst": True}
+ error = format.pop("errors", None) or "ignore"
+ return to_datetime(col, errors=error, **format)
else:
# Allow passing of formatting string for integers
# GH17855
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 0195b61d13798..497039de99196 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -369,6 +369,54 @@ def _load_test3_data(self):
self.test_frame3 = DataFrame(data, columns=columns)
+ def _load_types_test_data(self, data):
+ def _filter_to_flavor(flavor, df):
+ flavor_dtypes = {
+ "sqlite": {
+ "TextCol": "str",
+ "DateCol": "str",
+ "IntDateCol": "int64",
+ "IntDateOnlyCol": "int64",
+ "FloatCol": "float",
+ "IntCol": "int64",
+ "BoolCol": "int64",
+ "IntColWithNull": "float",
+ "BoolColWithNull": "float",
+ },
+ "mysql": {
+ "TextCol": "str",
+ "DateCol": "str",
+ "IntDateCol": "int64",
+ "IntDateOnlyCol": "int64",
+ "FloatCol": "float",
+ "IntCol": "int64",
+ "BoolCol": "bool",
+ "IntColWithNull": "float",
+ "BoolColWithNull": "float",
+ },
+ "postgresql": {
+ "TextCol": "str",
+ "DateCol": "str",
+ "DateColWithTz": "str",
+ "IntDateCol": "int64",
+ "IntDateOnlyCol": "int64",
+ "FloatCol": "float",
+ "IntCol": "int64",
+ "BoolCol": "bool",
+ "IntColWithNull": "float",
+ "BoolColWithNull": "float",
+ },
+ }
+
+ dtypes = flavor_dtypes[flavor]
+ return df[dtypes.keys()].astype(dtypes)
+
+ df = DataFrame(data)
+ self.types_test = {
+ flavor: _filter_to_flavor(flavor, df)
+ for flavor in ("sqlite", "mysql", "postgresql")
+ }
+
def _load_raw_sql(self):
self.drop_table("types_test_data")
self._get_exec().execute(SQL_STRINGS["create_test_types"][self.flavor])
@@ -405,6 +453,8 @@ def _load_raw_sql(self):
ins["query"], [d[field] for field in ins["fields"]]
)
+ self._load_types_test_data(data)
+
def _count_rows(self, table_name):
result = (
self._get_exec()
@@ -741,6 +791,36 @@ def test_date_parsing(self):
Timestamp("2010-12-12"),
]
+ @pytest.mark.parametrize("error", ["ignore", "raise", "coerce"])
+ @pytest.mark.parametrize(
+ "read_sql, text, mode",
+ [
+ (sql.read_sql, "SELECT * FROM types_test_data", ("sqlalchemy", "fallback")),
+ (sql.read_sql, "types_test_data", ("sqlalchemy")),
+ (
+ sql.read_sql_query,
+ "SELECT * FROM types_test_data",
+ ("sqlalchemy", "fallback"),
+ ),
+ (sql.read_sql_table, "types_test_data", ("sqlalchemy")),
+ ],
+ )
+ def test_custom_dateparsing_error(self, read_sql, text, mode, error):
+ if self.mode in mode:
+ expected = self.types_test[self.flavor].astype(
+ {"DateCol": "datetime64[ns]"}
+ )
+
+ result = read_sql(
+ text,
+ con=self.conn,
+ parse_dates={
+ "DateCol": {"errors": error},
+ },
+ )
+
+ tm.assert_frame_equal(result, expected)
+
def test_date_and_index(self):
# Test case where same column appears in parse_date and index_col
| - [x] closes #35185
- [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/37823 | 2020-11-13T21:31:54Z | 2020-12-14T01:41:44Z | 2020-12-14T01:41:44Z | 2020-12-14T01:41:53Z |
CI: pin build to use pyarrow==1.0 | diff --git a/ci/deps/azure-38-locale.yaml b/ci/deps/azure-38-locale.yaml
index 8ce58e07a8542..f879111a32e67 100644
--- a/ci/deps/azure-38-locale.yaml
+++ b/ci/deps/azure-38-locale.yaml
@@ -34,7 +34,7 @@ dependencies:
- xlsxwriter
- xlwt
- moto
- - pyarrow>=0.15
+ - pyarrow=1.0.0
- pip
- pip:
- pyxlsb
| closes #37306
@jorisvandenbossche picked build at random. we can discuss here what the preferences are? cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/37822 | 2020-11-13T20:51:04Z | 2020-11-14T02:22:23Z | 2020-11-14T02:22:23Z | 2020-11-14T13:55:01Z |
Deprecate partial slicing of unordered DatetimeIndex when both keys are not present | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 09cb024cbd95c..b5fbd277a3228 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -352,7 +352,7 @@ Deprecations
- :class:`Index` methods ``&``, ``|``, and ``^`` behaving as the set operations :meth:`Index.intersection`, :meth:`Index.union`, and :meth:`Index.symmetric_difference`, respectively, are deprecated and in the future will behave as pointwise boolean operations matching :class:`Series` behavior. Use the named set methods instead (:issue:`36758`)
- :meth:`Categorical.is_dtype_equal` and :meth:`CategoricalIndex.is_dtype_equal` are deprecated, will be removed in a future version (:issue:`37545`)
- :meth:`Series.slice_shift` and :meth:`DataFrame.slice_shift` are deprecated, use :meth:`Series.shift` or :meth:`DataFrame.shift` instead (:issue:`37601`)
-
+- Partial slicing on unordered :class:`DatetimeIndexes` with keys, which are not in Index is deprecated and will be removed in a future version (:issue:`18531`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 9744eb0ecbb88..a1a1a83555f95 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -803,14 +803,25 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None):
end is None or isinstance(end, str)
):
mask = np.array(True)
+ deprecation_mask = np.array(True)
if start is not None:
start_casted = self._maybe_cast_slice_bound(start, "left", kind)
mask = start_casted <= self
+ deprecation_mask = start_casted == self
if end is not None:
end_casted = self._maybe_cast_slice_bound(end, "right", kind)
mask = (self <= end_casted) & mask
-
+ deprecation_mask = (end_casted == self) | deprecation_mask
+
+ if not deprecation_mask.any():
+ warnings.warn(
+ "Value based partial slicing on non-monotonic DatetimeIndexes "
+ "with non-existing keys is deprecated and will raise a "
+ "KeyError in a future Version.",
+ FutureWarning,
+ stacklevel=5,
+ )
indexer = mask.nonzero()[0][::step]
if len(indexer) == len(self):
return slice(None)
diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py
index 57dc46e1fb415..05ee67eee0da5 100644
--- a/pandas/tests/indexes/datetimes/test_partial_slicing.py
+++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py
@@ -312,17 +312,22 @@ def test_partial_slicing_with_multiindex(self):
def test_partial_slice_doesnt_require_monotonicity(self):
# For historical reasons.
- s = Series(np.arange(10), date_range("2014-01-01", periods=10))
+ ser = Series(np.arange(10), date_range("2014-01-01", periods=10))
- nonmonotonic = s[[3, 5, 4]]
+ nonmonotonic = ser[[3, 5, 4]]
expected = nonmonotonic.iloc[:0]
timestamp = Timestamp("2014-01-10")
+ with tm.assert_produces_warning(FutureWarning):
+ result = nonmonotonic["2014-01-10":]
+ tm.assert_series_equal(result, expected)
- tm.assert_series_equal(nonmonotonic["2014-01-10":], expected)
with pytest.raises(KeyError, match=r"Timestamp\('2014-01-10 00:00:00'\)"):
nonmonotonic[timestamp:]
- tm.assert_series_equal(nonmonotonic.loc["2014-01-10":], expected)
+ with tm.assert_produces_warning(FutureWarning):
+ result = nonmonotonic.loc["2014-01-10":]
+ tm.assert_series_equal(result, expected)
+
with pytest.raises(KeyError, match=r"Timestamp\('2014-01-10 00:00:00'\)"):
nonmonotonic.loc[timestamp:]
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 9aab867df4b17..b45eddc3ac49c 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1564,6 +1564,15 @@ def test_loc_getitem_slice_label_td64obj(self, start, stop, expected_slice):
expected = ser.iloc[expected_slice]
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("start", ["2018", "2020"])
+ def test_loc_getitem_slice_unordered_dt_index(self, frame_or_series, start):
+ obj = frame_or_series(
+ [1, 2, 3],
+ index=[Timestamp("2016"), Timestamp("2019"), Timestamp("2017")],
+ )
+ with tm.assert_produces_warning(FutureWarning):
+ obj.loc[start:"2022"]
+
class TestLocBooleanMask:
def test_loc_setitem_bool_mask_timedeltaindex(self):
diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py
index 44fb8dc519322..71ddf72562f36 100644
--- a/pandas/tests/series/indexing/test_datetime.py
+++ b/pandas/tests/series/indexing/test_datetime.py
@@ -526,7 +526,8 @@ def compare(slobj):
tm.assert_series_equal(result, expected)
compare(slice("2011-01-01", "2011-01-15"))
- compare(slice("2010-12-30", "2011-01-15"))
+ with tm.assert_produces_warning(FutureWarning):
+ compare(slice("2010-12-30", "2011-01-15"))
compare(slice("2011-01-01", "2011-01-16"))
# partial ranges
| - [x] xref #18531
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
cc @jreback @jorisvandenbossche
This would deprecate #37796 before removing it. | https://api.github.com/repos/pandas-dev/pandas/pulls/37819 | 2020-11-13T19:13:00Z | 2020-11-15T17:39:05Z | 2020-11-15T17:39:05Z | 2020-11-15T17:41:54Z |
ENH: storage_options for to_excel | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 49e992b14293e..3392b64890cb7 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2028,9 +2028,9 @@ def _repr_data_resource_(self):
def to_excel(
self,
excel_writer,
- sheet_name="Sheet1",
- na_rep="",
- float_format=None,
+ sheet_name: str = "Sheet1",
+ na_rep: str = "",
+ float_format: Optional[str] = None,
columns=None,
header=True,
index=True,
@@ -2043,6 +2043,7 @@ def to_excel(
inf_rep="inf",
verbose=True,
freeze_panes=None,
+ storage_options: StorageOptions = None,
) -> None:
"""
Write {klass} to an Excel sheet.
@@ -2059,7 +2060,7 @@ def to_excel(
Parameters
----------
- excel_writer : str or ExcelWriter object
+ excel_writer : path-like, file-like, or ExcelWriter object
File path or existing ExcelWriter.
sheet_name : str, default 'Sheet1'
Name of sheet which will contain DataFrame.
@@ -2100,6 +2101,12 @@ def to_excel(
freeze_panes : tuple of int (length 2), optional
Specifies the one-based bottommost row and rightmost column that
is to be frozen.
+ storage_options : dict, optional
+ Extra options that make sense for a particular storage connection, e.g.
+ host, port, username, password, etc., if using a URL that will
+ be parsed by ``fsspec``, e.g., starting "s3://", "gcs://".
+
+ .. versionadded:: 1.2.0
See Also
--------
@@ -2174,6 +2181,7 @@ def to_excel(
startcol=startcol,
freeze_panes=freeze_panes,
engine=engine,
+ storage_options=storage_options,
)
@final
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index c2e9828e3ea42..425b1da33dbb9 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -3,12 +3,12 @@
from io import BufferedIOBase, BytesIO, RawIOBase
import os
from textwrap import fill
-from typing import Any, Mapping, Union
+from typing import Any, Dict, Mapping, Union, cast
from pandas._config import config
from pandas._libs.parsers import STR_NA_VALUES
-from pandas._typing import StorageOptions
+from pandas._typing import Buffer, FilePathOrBuffer, StorageOptions
from pandas.errors import EmptyDataError
from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments
@@ -567,6 +567,12 @@ class ExcelWriter(metaclass=abc.ABCMeta):
File mode to use (write or append). Append does not work with fsspec URLs.
.. versionadded:: 0.24.0
+ storage_options : dict, optional
+ Extra options that make sense for a particular storage connection, e.g.
+ host, port, username, password, etc., if using a URL that will
+ be parsed by ``fsspec``, e.g., starting "s3://", "gcs://".
+
+ .. versionadded:: 1.2.0
Attributes
----------
@@ -710,11 +716,12 @@ def save(self):
def __init__(
self,
- path,
+ path: Union[FilePathOrBuffer, "ExcelWriter"],
engine=None,
date_format=None,
datetime_format=None,
- mode="w",
+ mode: str = "w",
+ storage_options: StorageOptions = None,
**engine_kwargs,
):
# validate that this engine can handle the extension
@@ -729,10 +736,13 @@ def __init__(
# the excel backend first read the existing file and then write any data to it
mode = mode.replace("a", "r+")
- self.handles = IOHandles(path, compression={"copression": None})
+ # cast ExcelWriter to avoid adding 'if self.handles is not None'
+ self.handles = IOHandles(cast(Buffer, path), compression={"copression": None})
if not isinstance(path, ExcelWriter):
- self.handles = get_handle(path, mode, is_text=False)
- self.sheets = {}
+ self.handles = get_handle(
+ path, mode, storage_options=storage_options, is_text=False
+ )
+ self.sheets: Dict[str, Any] = {}
self.cur_sheet = None
if date_format is None:
diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py
index c19d51540d2dd..f9a08bf862644 100644
--- a/pandas/io/excel/_odswriter.py
+++ b/pandas/io/excel/_odswriter.py
@@ -3,6 +3,7 @@
from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union
import pandas._libs.json as json
+from pandas._typing import StorageOptions
from pandas.io.excel._base import ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -14,7 +15,12 @@ class ODSWriter(ExcelWriter):
supported_extensions = (".ods",)
def __init__(
- self, path: str, engine: Optional[str] = None, mode: str = "w", **engine_kwargs
+ self,
+ path: str,
+ engine: Optional[str] = None,
+ mode: str = "w",
+ storage_options: StorageOptions = None,
+ **engine_kwargs,
):
from odf.opendocument import OpenDocumentSpreadsheet
@@ -23,7 +29,9 @@ def __init__(
if mode == "a":
raise ValueError("Append mode is not supported with odf!")
- super().__init__(path, mode=mode, **engine_kwargs)
+ super().__init__(
+ path, mode=mode, storage_options=storage_options, **engine_kwargs
+ )
self.book = OpenDocumentSpreadsheet()
self._style_dict: Dict[str, str] = {}
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index f643037dc216a..7de958df206d5 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -16,11 +16,20 @@ class OpenpyxlWriter(ExcelWriter):
engine = "openpyxl"
supported_extensions = (".xlsx", ".xlsm")
- def __init__(self, path, engine=None, mode="w", **engine_kwargs):
+ def __init__(
+ self,
+ path,
+ engine=None,
+ mode: str = "w",
+ storage_options: StorageOptions = None,
+ **engine_kwargs,
+ ):
# Use the openpyxl module as the Excel writer.
from openpyxl.workbook import Workbook
- super().__init__(path, mode=mode, **engine_kwargs)
+ super().__init__(
+ path, mode=mode, storage_options=storage_options, **engine_kwargs
+ )
# ExcelWriter replaced "a" by "r+" to allow us to first read the excel file from
# the file and later write to it
diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py
index 77b631a41371e..d7bbec578d89d 100644
--- a/pandas/io/excel/_xlsxwriter.py
+++ b/pandas/io/excel/_xlsxwriter.py
@@ -1,6 +1,7 @@
from typing import Dict, List, Tuple
import pandas._libs.json as json
+from pandas._typing import StorageOptions
from pandas.io.excel._base import ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -168,7 +169,8 @@ def __init__(
engine=None,
date_format=None,
datetime_format=None,
- mode="w",
+ mode: str = "w",
+ storage_options: StorageOptions = None,
**engine_kwargs,
):
# Use the xlsxwriter module as the Excel writer.
@@ -183,6 +185,7 @@ def __init__(
date_format=date_format,
datetime_format=datetime_format,
mode=mode,
+ storage_options=storage_options,
**engine_kwargs,
)
diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py
index 7f0ce3844c099..9ede7cd0c2b95 100644
--- a/pandas/io/excel/_xlwt.py
+++ b/pandas/io/excel/_xlwt.py
@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING, Dict
import pandas._libs.json as json
+from pandas._typing import StorageOptions
from pandas.io.excel._base import ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -13,7 +14,15 @@ class XlwtWriter(ExcelWriter):
engine = "xlwt"
supported_extensions = (".xls",)
- def __init__(self, path, engine=None, encoding=None, mode="w", **engine_kwargs):
+ def __init__(
+ self,
+ path,
+ engine=None,
+ encoding=None,
+ mode: str = "w",
+ storage_options: StorageOptions = None,
+ **engine_kwargs,
+ ):
# Use the xlwt module as the Excel writer.
import xlwt
@@ -22,7 +31,9 @@ def __init__(self, path, engine=None, encoding=None, mode="w", **engine_kwargs):
if mode == "a":
raise ValueError("Append mode is not supported with xlwt!")
- super().__init__(path, mode=mode, **engine_kwargs)
+ super().__init__(
+ path, mode=mode, storage_options=storage_options, **engine_kwargs
+ )
if encoding is None:
encoding = "ascii"
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index 0916494d8ab60..c6179f5c034c7 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -10,7 +10,7 @@
import numpy as np
-from pandas._typing import Label
+from pandas._typing import Label, StorageOptions
from pandas.core.dtypes import missing
from pandas.core.dtypes.common import is_float, is_scalar
@@ -19,7 +19,6 @@
from pandas import DataFrame, Index, MultiIndex, PeriodIndex
import pandas.core.common as com
-from pandas.io.common import stringify_path
from pandas.io.formats.css import CSSResolver, CSSWarning
from pandas.io.formats.format import get_level_lengths
from pandas.io.formats.printing import pprint_thing
@@ -785,9 +784,10 @@ def write(
startcol=0,
freeze_panes=None,
engine=None,
+ storage_options: StorageOptions = None,
):
"""
- writer : string or ExcelWriter object
+ writer : path-like, file-like, or ExcelWriter object
File path or existing ExcelWriter
sheet_name : string, default 'Sheet1'
Name of sheet which will contain DataFrame
@@ -802,6 +802,12 @@ def write(
write engine to use if writer is a path - you can also set this
via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``,
and ``io.excel.xlsm.writer``.
+ storage_options : dict, optional
+ Extra options that make sense for a particular storage connection, e.g.
+ host, port, username, password, etc., if using a URL that will
+ be parsed by ``fsspec``, e.g., starting "s3://", "gcs://".
+
+ .. versionadded:: 1.2.0
"""
from pandas.io.excel import ExcelWriter
@@ -819,7 +825,7 @@ def write(
# abstract class 'ExcelWriter' with abstract attributes 'engine',
# 'save', 'supported_extensions' and 'write_cells' [abstract]
writer = ExcelWriter( # type: ignore[abstract]
- stringify_path(writer), engine=engine
+ writer, engine=engine, storage_options=storage_options
)
need_save = True
diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py
index 312ea5abdfe39..c5767c5080ddd 100644
--- a/pandas/tests/io/test_fsspec.py
+++ b/pandas/tests/io/test_fsspec.py
@@ -124,6 +124,18 @@ def test_csv_options(fsspectest):
assert fsspectest.test[0] == "csv_read"
+@pytest.mark.parametrize("extension", ["xlsx", "xls"])
+def test_excel_options(fsspectest, extension):
+ df = DataFrame({"a": [0]})
+
+ path = f"testmem://test/test.{extension}"
+
+ df.to_excel(path, storage_options={"test": "write"}, index=False)
+ assert fsspectest.test[0] == "write"
+ read_excel(path, storage_options={"test": "read"})
+ assert fsspectest.test[0] == "read"
+
+
@td.skip_if_no("fastparquet")
def test_to_parquet_new_file(monkeypatch, cleared_fs):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
| - [ ] ref #33987 (follow up to #37639)
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry: not added, already implied in whatsnew of #37639? | https://api.github.com/repos/pandas-dev/pandas/pulls/37818 | 2020-11-13T19:06:20Z | 2020-11-14T17:05:51Z | 2020-11-14T17:05:51Z | 2020-11-14T18:47:34Z |
TYP: _concat_same_type method of EA | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index ffb892ed7e505..7eaadecbd6491 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional, Sequence, TypeVar
+from typing import Any, Optional, Sequence, Type, TypeVar
import numpy as np
@@ -170,7 +170,11 @@ def unique(self: NDArrayBackedExtensionArrayT) -> NDArrayBackedExtensionArrayT:
@classmethod
@doc(ExtensionArray._concat_same_type)
- def _concat_same_type(cls, to_concat, axis: int = 0):
+ def _concat_same_type(
+ cls: Type[NDArrayBackedExtensionArrayT],
+ to_concat: Sequence[NDArrayBackedExtensionArrayT],
+ axis: int = 0,
+ ) -> NDArrayBackedExtensionArrayT:
dtypes = {str(x.dtype) for x in to_concat}
if len(dtypes) != 1:
raise ValueError("to_concat must have the same dtype (tz)", dtypes)
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 0b01ea305b73c..0968545a6b8a4 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -7,12 +7,23 @@
without warning.
"""
import operator
-from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union, cast
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+ cast,
+)
import numpy as np
from pandas._libs import lib
-from pandas._typing import ArrayLike, Shape, TypeVar
+from pandas._typing import ArrayLike, Shape
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
@@ -1132,8 +1143,8 @@ def ravel(self, order="C") -> "ExtensionArray":
@classmethod
def _concat_same_type(
- cls, to_concat: Sequence["ExtensionArray"]
- ) -> "ExtensionArray":
+ cls: Type[ExtensionArrayT], to_concat: Sequence[ExtensionArrayT]
+ ) -> ExtensionArrayT:
"""
Concatenate multiple array of this dtype.
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 970163df908ec..67818e6cf8fae 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2,7 +2,7 @@
from functools import partial
import operator
from shutil import get_terminal_size
-from typing import Dict, Hashable, List, Type, Union, cast
+from typing import Dict, Hashable, List, Sequence, Type, TypeVar, Union, cast
from warnings import warn
import numpy as np
@@ -56,6 +56,8 @@
from pandas.io.formats import console
+CategoricalT = TypeVar("CategoricalT", bound="Categorical")
+
def _cat_compare_op(op):
opname = f"__{op.__name__}__"
@@ -2080,7 +2082,9 @@ def equals(self, other: object) -> bool:
return False
@classmethod
- def _concat_same_type(self, to_concat):
+ def _concat_same_type(
+ cls: Type[CategoricalT], to_concat: Sequence[CategoricalT], axis: int = 0
+ ) -> CategoricalT:
from pandas.core.dtypes.concat import union_categoricals
return union_categoricals(to_concat)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index aa386e8a264cd..0ce32fcd822e0 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -375,7 +375,11 @@ def view(self, dtype=None):
# ExtensionArray Interface
@classmethod
- def _concat_same_type(cls, to_concat, axis: int = 0):
+ def _concat_same_type(
+ cls: Type[DatetimeLikeArrayT],
+ to_concat: Sequence[DatetimeLikeArrayT],
+ axis: int = 0,
+ ) -> DatetimeLikeArrayT:
new_obj = super()._concat_same_type(to_concat, axis)
obj = to_concat[0]
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 5c1b4f1d781cd..d007bb112c86c 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,7 +1,7 @@
import operator
from operator import le, lt
import textwrap
-from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union, cast
+from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Type, TypeVar, Union, cast
import numpy as np
@@ -724,7 +724,9 @@ def equals(self, other) -> bool:
)
@classmethod
- def _concat_same_type(cls, to_concat):
+ def _concat_same_type(
+ cls: Type[IntervalArrayT], to_concat: Sequence[IntervalArrayT]
+ ) -> IntervalArrayT:
"""
Concatenate multiple IntervalArray
@@ -1470,10 +1472,19 @@ def _get_combined_data(
axis=1,
)
else:
- left = cast(Union["DatetimeArray", "TimedeltaArray"], left)
- right = cast(Union["DatetimeArray", "TimedeltaArray"], right)
- combined = type(left)._concat_same_type(
- [left.reshape(-1, 1), right.reshape(-1, 1)],
+ # error: Item "type" of "Union[Type[Index], Type[ExtensionArray]]" has
+ # no attribute "_concat_same_type" [union-attr]
+
+ # error: Unexpected keyword argument "axis" for "_concat_same_type" of
+ # "ExtensionArray" [call-arg]
+
+ # error: Item "Index" of "Union[Index, ExtensionArray]" has no
+ # attribute "reshape" [union-attr]
+
+ # error: Item "ExtensionArray" of "Union[Index, ExtensionArray]" has no
+ # attribute "reshape" [union-attr]
+ combined = type(left)._concat_same_type( # type: ignore[union-attr,call-arg]
+ [left.reshape(-1, 1), right.reshape(-1, 1)], # type: ignore[union-attr]
axis=1,
)
return combined
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 9cc4cc72e4c8e..a4b88427ceb05 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Optional, Tuple, Type, TypeVar
+from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Type, TypeVar
import numpy as np
@@ -261,7 +261,9 @@ def nbytes(self) -> int:
return self._data.nbytes + self._mask.nbytes
@classmethod
- def _concat_same_type(cls: Type[BaseMaskedArrayT], to_concat) -> BaseMaskedArrayT:
+ def _concat_same_type(
+ cls: Type[BaseMaskedArrayT], to_concat: Sequence[BaseMaskedArrayT]
+ ) -> BaseMaskedArrayT:
data = np.concatenate([x._data for x in to_concat])
mask = np.concatenate([x._mask for x in to_concat])
return cls(data, mask)
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index e3b28e2f47af2..c591f81390388 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -4,7 +4,7 @@
from collections import abc
import numbers
import operator
-from typing import Any, Callable, Type, TypeVar, Union
+from typing import Any, Callable, Sequence, Type, TypeVar, Union
import warnings
import numpy as np
@@ -946,7 +946,9 @@ def copy(self: SparseArrayT) -> SparseArrayT:
return self._simple_new(values, self.sp_index, self.dtype)
@classmethod
- def _concat_same_type(cls, to_concat):
+ def _concat_same_type(
+ cls: Type[SparseArrayT], to_concat: Sequence[SparseArrayT]
+ ) -> SparseArrayT:
fill_value = to_concat[0].fill_value
values = []
| some overlap with #37816 | https://api.github.com/repos/pandas-dev/pandas/pulls/37817 | 2020-11-13T18:35:17Z | 2020-11-14T16:54:28Z | 2020-11-14T16:54:28Z | 2020-11-15T11:36:16Z |
TYP: copy method of EAs | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index ddcf225d3585f..ffb892ed7e505 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -20,7 +20,9 @@
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_indexer
-_T = TypeVar("_T", bound="NDArrayBackedExtensionArray")
+NDArrayBackedExtensionArrayT = TypeVar(
+ "NDArrayBackedExtensionArrayT", bound="NDArrayBackedExtensionArray"
+)
class NDArrayBackedExtensionArray(ExtensionArray):
@@ -30,7 +32,9 @@ class NDArrayBackedExtensionArray(ExtensionArray):
_ndarray: np.ndarray
- def _from_backing_data(self: _T, arr: np.ndarray) -> _T:
+ def _from_backing_data(
+ self: NDArrayBackedExtensionArrayT, arr: np.ndarray
+ ) -> NDArrayBackedExtensionArrayT:
"""
Construct a new ExtensionArray `new_array` with `arr` as its _ndarray.
@@ -52,13 +56,13 @@ def _validate_scalar(self, value):
# ------------------------------------------------------------------------
def take(
- self: _T,
+ self: NDArrayBackedExtensionArrayT,
indices: Sequence[int],
*,
allow_fill: bool = False,
fill_value: Any = None,
axis: int = 0,
- ) -> _T:
+ ) -> NDArrayBackedExtensionArrayT:
if allow_fill:
fill_value = self._validate_fill_value(fill_value)
@@ -113,16 +117,20 @@ def size(self) -> int:
def nbytes(self) -> int:
return self._ndarray.nbytes
- def reshape(self: _T, *args, **kwargs) -> _T:
+ def reshape(
+ self: NDArrayBackedExtensionArrayT, *args, **kwargs
+ ) -> NDArrayBackedExtensionArrayT:
new_data = self._ndarray.reshape(*args, **kwargs)
return self._from_backing_data(new_data)
- def ravel(self: _T, *args, **kwargs) -> _T:
+ def ravel(
+ self: NDArrayBackedExtensionArrayT, *args, **kwargs
+ ) -> NDArrayBackedExtensionArrayT:
new_data = self._ndarray.ravel(*args, **kwargs)
return self._from_backing_data(new_data)
@property
- def T(self: _T) -> _T:
+ def T(self: NDArrayBackedExtensionArrayT) -> NDArrayBackedExtensionArrayT:
new_data = self._ndarray.T
return self._from_backing_data(new_data)
@@ -138,11 +146,13 @@ def equals(self, other) -> bool:
def _values_for_argsort(self):
return self._ndarray
- def copy(self: _T) -> _T:
+ def copy(self: NDArrayBackedExtensionArrayT) -> NDArrayBackedExtensionArrayT:
new_data = self._ndarray.copy()
return self._from_backing_data(new_data)
- def repeat(self: _T, repeats, axis=None) -> _T:
+ def repeat(
+ self: NDArrayBackedExtensionArrayT, repeats, axis=None
+ ) -> NDArrayBackedExtensionArrayT:
"""
Repeat elements of an array.
@@ -154,7 +164,7 @@ def repeat(self: _T, repeats, axis=None) -> _T:
new_data = self._ndarray.repeat(repeats, axis=axis)
return self._from_backing_data(new_data)
- def unique(self: _T) -> _T:
+ def unique(self: NDArrayBackedExtensionArrayT) -> NDArrayBackedExtensionArrayT:
new_data = unique(self._ndarray)
return self._from_backing_data(new_data)
@@ -216,7 +226,9 @@ def __getitem__(self, key):
return result
@doc(ExtensionArray.fillna)
- def fillna(self: _T, value=None, method=None, limit=None) -> _T:
+ def fillna(
+ self: NDArrayBackedExtensionArrayT, value=None, method=None, limit=None
+ ) -> NDArrayBackedExtensionArrayT:
value, method = validate_fillna_kwargs(value, method)
mask = self.isna()
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index afbddc53804ac..0b01ea305b73c 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -12,7 +12,7 @@
import numpy as np
from pandas._libs import lib
-from pandas._typing import ArrayLike, Shape
+from pandas._typing import ArrayLike, Shape, TypeVar
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
@@ -37,6 +37,8 @@
_extension_array_shared_docs: Dict[str, str] = dict()
+ExtensionArrayT = TypeVar("ExtensionArrayT", bound="ExtensionArray")
+
class ExtensionArray:
"""
@@ -1016,7 +1018,7 @@ def take(self, indices, allow_fill=False, fill_value=None):
# pandas.api.extensions.take
raise AbstractMethodError(self)
- def copy(self) -> "ExtensionArray":
+ def copy(self: ExtensionArrayT) -> ExtensionArrayT:
"""
Return a copy of the array.
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 977e4abff4287..5c1b4f1d781cd 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,7 +1,7 @@
import operator
from operator import le, lt
import textwrap
-from typing import TYPE_CHECKING, Optional, Tuple, Union, cast
+from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union, cast
import numpy as np
@@ -56,6 +56,8 @@
from pandas import Index
from pandas.core.arrays import DatetimeArray, TimedeltaArray
+IntervalArrayT = TypeVar("IntervalArrayT", bound="IntervalArray")
+
_interval_shared_docs = {}
_shared_docs_kwargs = dict(
@@ -745,7 +747,7 @@ def _concat_same_type(cls, to_concat):
combined = _get_combined_data(left, right) # TODO: 1-stage concat
return cls._simple_new(combined, closed=closed)
- def copy(self):
+ def copy(self: IntervalArrayT) -> IntervalArrayT:
"""
Return a copy of the array.
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index d976526955ac2..e3b28e2f47af2 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -4,7 +4,7 @@
from collections import abc
import numbers
import operator
-from typing import Any, Callable, Union
+from typing import Any, Callable, Type, TypeVar, Union
import warnings
import numpy as np
@@ -56,6 +56,7 @@
# ----------------------------------------------------------------------------
# Array
+SparseArrayT = TypeVar("SparseArrayT", bound="SparseArray")
_sparray_doc_kwargs = dict(klass="SparseArray")
@@ -397,8 +398,11 @@ def __init__(
@classmethod
def _simple_new(
- cls, sparse_array: np.ndarray, sparse_index: SparseIndex, dtype: SparseDtype
- ) -> "SparseArray":
+ cls: Type[SparseArrayT],
+ sparse_array: np.ndarray,
+ sparse_index: SparseIndex,
+ dtype: SparseDtype,
+ ) -> SparseArrayT:
new = object.__new__(cls)
new._sparse_index = sparse_index
new._sparse_values = sparse_array
@@ -937,7 +941,7 @@ def searchsorted(self, v, side="left", sorter=None):
v = np.asarray(v)
return np.asarray(self, dtype=self.dtype.subtype).searchsorted(v, side, sorter)
- def copy(self):
+ def copy(self: SparseArrayT) -> SparseArrayT:
values = self.sp_values.copy()
return self._simple_new(values, self.sp_index, self.dtype)
| https://api.github.com/repos/pandas-dev/pandas/pulls/37816 | 2020-11-13T17:40:38Z | 2020-11-14T02:20:11Z | 2020-11-14T02:20:10Z | 2020-11-14T09:35:48Z | |
REF: define nanargminmax without values_for_argsort | diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index e390229b5dcba..2a0da8b0fb35c 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -31,6 +31,7 @@
if TYPE_CHECKING:
from pandas import MultiIndex
+ from pandas.core.arrays import ExtensionArray
from pandas.core.indexes.base import Index
_INT64_MAX = np.iinfo(np.int64).max
@@ -390,7 +391,7 @@ def nargsort(
return indexer
-def nargminmax(values, method: str):
+def nargminmax(values: "ExtensionArray", method: str) -> int:
"""
Implementation of np.argmin/argmax but for ExtensionArray and which
handles missing values.
@@ -405,16 +406,20 @@ def nargminmax(values, method: str):
int
"""
assert method in {"argmax", "argmin"}
- func = np.argmax if method == "argmax" else np.argmin
- mask = np.asarray(isna(values))
- values = values._values_for_argsort()
+ mask = np.asarray(values.isna())
+ if mask.all():
+ # Use same exception message we would get from numpy
+ raise ValueError(f"attempt to get {method} of an empty sequence")
- idx = np.arange(len(values))
- non_nans = values[~mask]
- non_nan_idx = idx[~mask]
+ if method == "argmax":
+ # Use argsort with ascending=False so that if more than one entry
+ # achieves the maximum, we take the first such occurence.
+ sorters = values.argsort(ascending=False)
+ else:
+ sorters = values.argsort(ascending=True)
- return non_nan_idx[func(non_nans)]
+ return sorters[0]
def _ensure_key_mapped_multiindex(
| https://api.github.com/repos/pandas-dev/pandas/pulls/37815 | 2020-11-13T16:49:20Z | 2020-11-14T17:49:30Z | 2020-11-14T17:49:30Z | 2020-12-01T07:31:33Z | |
Backport PR #37812 on branch 1.1.x (CI: The `set-env` and `add-path` commands are deprecated and will be disabled on November 16th.) | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 149acef72db26..af9f41062d096 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,7 +18,7 @@ jobs:
steps:
- name: Setting conda path
- run: echo "::add-path::${HOME}/miniconda3/bin"
+ run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- name: Checkout
uses: actions/checkout@v1
@@ -104,7 +104,7 @@ jobs:
steps:
- name: Setting conda path
- run: echo "::set-env name=PATH::${HOME}/miniconda3/bin:${PATH}"
+ run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- name: Checkout
uses: actions/checkout@v1
| Backport PR #37812: CI: The `set-env` and `add-path` commands are deprecated and will be disabled on November 16th. | https://api.github.com/repos/pandas-dev/pandas/pulls/37814 | 2020-11-13T16:21:17Z | 2020-11-13T18:43:40Z | 2020-11-13T18:43:40Z | 2020-11-13T18:43:40Z |
CI: The `set-env` and `add-path` commands are deprecated and will be disabled on November 16th. | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b391871b18245..c00cec450c85e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,7 +18,7 @@ jobs:
steps:
- name: Setting conda path
- run: echo "::add-path::${HOME}/miniconda3/bin"
+ run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- name: Checkout
uses: actions/checkout@v1
@@ -98,7 +98,7 @@ jobs:
steps:
- name: Setting conda path
- run: echo "::set-env name=PATH::${HOME}/miniconda3/bin:${PATH}"
+ run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- name: Checkout
uses: actions/checkout@v1
| https://github.com/pandas-dev/pandas/actions/runs/361523610 | https://api.github.com/repos/pandas-dev/pandas/pulls/37812 | 2020-11-13T12:34:36Z | 2020-11-13T15:13:40Z | 2020-11-13T15:13:40Z | 2020-11-13T16:20:36Z |
DOC: capitalize Python as proper noun | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index 4261d79a5e3f5..41b2b7405fcb5 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -442,7 +442,7 @@ Some other important things to know about the docs:
contributing_docstring.rst
-* The tutorials make heavy use of the `ipython directive
+* The tutorials make heavy use of the `IPython directive
<https://matplotlib.org/sampledoc/ipython_directive.html>`_ sphinx extension.
This directive lets you put code in the documentation which will be run
during the doc build. For example::
diff --git a/doc/source/development/contributing_docstring.rst b/doc/source/development/contributing_docstring.rst
index 26cdd0687706c..623d1e8d45565 100644
--- a/doc/source/development/contributing_docstring.rst
+++ b/doc/source/development/contributing_docstring.rst
@@ -63,14 +63,14 @@ The first conventions every Python docstring should follow are defined in
`PEP-257 <https://www.python.org/dev/peps/pep-0257/>`_.
As PEP-257 is quite broad, other more specific standards also exist. In the
-case of pandas, the numpy docstring convention is followed. These conventions are
+case of pandas, the NumPy docstring convention is followed. These conventions are
explained in this document:
* `numpydoc docstring guide <https://numpydoc.readthedocs.io/en/latest/format.html>`_
(which is based in the original `Guide to NumPy/SciPy documentation
<https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_)
-numpydoc is a Sphinx extension to support the numpy docstring convention.
+numpydoc is a Sphinx extension to support the NumPy docstring convention.
The standard uses reStructuredText (reST). reStructuredText is a markup
language that allows encoding styles in plain text files. Documentation
@@ -401,7 +401,7 @@ DataFrame:
* pandas.Categorical
* pandas.arrays.SparseArray
-If the exact type is not relevant, but must be compatible with a numpy
+If the exact type is not relevant, but must be compatible with a NumPy
array, array-like can be specified. If Any type that can be iterated is
accepted, iterable can be used:
@@ -819,7 +819,7 @@ positional arguments ``head(3)``.
"""
A sample DataFrame method.
- Do not import numpy and pandas.
+ Do not import NumPy and pandas.
Try to use meaningful data, when it makes the example easier
to understand.
@@ -854,7 +854,7 @@ Tips for getting your examples pass the doctests
Getting the examples pass the doctests in the validation script can sometimes
be tricky. Here are some attention points:
-* Import all needed libraries (except for pandas and numpy, those are already
+* Import all needed libraries (except for pandas and NumPy, those are already
imported as ``import pandas as pd`` and ``import numpy as np``) and define
all variables you use in the example.
diff --git a/doc/source/development/extending.rst b/doc/source/development/extending.rst
index 77fe930cf21e3..d4219296f5795 100644
--- a/doc/source/development/extending.rst
+++ b/doc/source/development/extending.rst
@@ -219,7 +219,7 @@ and re-boxes it if necessary.
If applicable, we highly recommend that you implement ``__array_ufunc__`` in your
extension array to avoid coercion to an ndarray. See
-`the numpy documentation <https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html>`__
+`the NumPy documentation <https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html>`__
for an example.
As part of your implementation, we require that you defer to pandas when a pandas
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 670905f6587bc..be32c5c14fdfc 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -174,7 +174,7 @@ invoked with the following command
dtale.show(df)
-D-Tale integrates seamlessly with jupyter notebooks, python terminals, kaggle
+D-Tale integrates seamlessly with Jupyter notebooks, Python terminals, Kaggle
& Google Colab. Here are some demos of the `grid <http://alphatechadmin.pythonanywhere.com/>`__
and `chart-builder <http://alphatechadmin.pythonanywhere.com/charts/4?chart_type=surface&query=&x=date&z=Col0&agg=raw&cpg=false&y=%5B%22security_id%22%5D>`__.
@@ -421,7 +421,7 @@ If also displays progress bars.
`Vaex <https://docs.vaex.io/>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Increasingly, packages are being built on top of pandas to address specific needs in data preparation, analysis and visualization. Vaex is a python library for Out-of-Core DataFrames (similar to pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (10\ :sup:`9`) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
+Increasingly, packages are being built on top of pandas to address specific needs in data preparation, analysis and visualization. Vaex is a Python library for Out-of-Core DataFrames (similar to pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (10\ :sup:`9`) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
* vaex.from_pandas
* vaex.to_pandas_df
diff --git a/doc/source/getting_started/intro_tutorials/04_plotting.rst b/doc/source/getting_started/intro_tutorials/04_plotting.rst
index 991c2bbe0fba6..b7a566a35084d 100644
--- a/doc/source/getting_started/intro_tutorials/04_plotting.rst
+++ b/doc/source/getting_started/intro_tutorials/04_plotting.rst
@@ -131,8 +131,8 @@ standard Python to get an overview of the available plot methods:
]
.. note::
- In many development environments as well as ipython and
- jupyter notebook, use the TAB button to get an overview of the available
+ In many development environments as well as IPython and
+ Jupyter Notebook, use the TAB button to get an overview of the available
methods, for example ``air_quality.plot.`` + TAB.
One of the options is :meth:`DataFrame.plot.box`, which refers to a
diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst
index 08f83a4674ada..cf548ba5d1133 100644
--- a/doc/source/user_guide/10min.rst
+++ b/doc/source/user_guide/10min.rst
@@ -239,13 +239,13 @@ Select via the position of the passed integers:
df.iloc[3]
-By integer slices, acting similar to numpy/python:
+By integer slices, acting similar to numpy/Python:
.. ipython:: python
df.iloc[3:5, 0:2]
-By lists of integer position locations, similar to the numpy/python style:
+By lists of integer position locations, similar to the NumPy/Python style:
.. ipython:: python
diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst
index 53fabf94e24e0..a21e5180004b2 100644
--- a/doc/source/user_guide/basics.rst
+++ b/doc/source/user_guide/basics.rst
@@ -845,7 +845,7 @@ For example, we can fit a regression using statsmodels. Their API expects a form
The pipe method is inspired by unix pipes and more recently dplyr_ and magrittr_, which
have introduced the popular ``(%>%)`` (read pipe) operator for R_.
-The implementation of ``pipe`` here is quite clean and feels right at home in python.
+The implementation of ``pipe`` here is quite clean and feels right at home in Python.
We encourage you to view the source code of :meth:`~DataFrame.pipe`.
.. _dplyr: https://github.com/hadley/dplyr
@@ -2203,7 +2203,7 @@ You can use the :meth:`~DataFrame.astype` method to explicitly convert dtypes fr
even if the dtype was unchanged (pass ``copy=False`` to change this behavior). In addition, they will raise an
exception if the astype operation is invalid.
-Upcasting is always according to the **numpy** rules. If two different dtypes are involved in an operation,
+Upcasting is always according to the **NumPy** rules. If two different dtypes are involved in an operation,
then the more *general* one will be used as the result of the operation.
.. ipython:: python
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst
index 939acf10d6c0b..5a6f56388dee5 100644
--- a/doc/source/user_guide/cookbook.rst
+++ b/doc/source/user_guide/cookbook.rst
@@ -18,9 +18,6 @@ above what the in-line examples offer.
pandas (pd) and Numpy (np) are the only two abbreviated imported modules. The rest are kept
explicitly imported for newer users.
-These examples are written for Python 3. Minor tweaks might be necessary for earlier python
-versions.
-
Idioms
------
@@ -71,7 +68,7 @@ Or use pandas where after you've set up a mask
)
df.where(df_mask, -1000)
-`if-then-else using numpy's where()
+`if-then-else using NumPy's where()
<https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column>`__
.. ipython:: python
@@ -1013,7 +1010,7 @@ The :ref:`Plotting <visualization>` docs.
`Setting x-axis major and minor labels
<https://stackoverflow.com/questions/12945971/pandas-timeseries-plot-setting-x-axis-major-and-minor-ticks-and-labels>`__
-`Plotting multiple charts in an ipython notebook
+`Plotting multiple charts in an IPython Jupyter notebook
<https://stackoverflow.com/questions/16392921/make-more-than-one-chart-in-same-ipython-notebook-cell>`__
`Creating a multi-line plot
diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst
index cc8de98165fac..39257c06feffe 100644
--- a/doc/source/user_guide/enhancingperf.rst
+++ b/doc/source/user_guide/enhancingperf.rst
@@ -96,7 +96,7 @@ hence we'll concentrate our efforts cythonizing these two functions.
Plain Cython
~~~~~~~~~~~~
-First we're going to need to import the Cython magic function to ipython:
+First we're going to need to import the Cython magic function to IPython:
.. ipython:: python
:okwarning:
@@ -123,7 +123,7 @@ is here to distinguish between function versions):
.. note::
If you're having trouble pasting the above into your ipython, you may need
- to be using bleeding edge ipython for paste to play well with cell magics.
+ to be using bleeding edge IPython for paste to play well with cell magics.
.. code-block:: ipython
@@ -160,7 +160,7 @@ We get another huge improvement simply by providing type information:
In [4]: %timeit df.apply(lambda x: integrate_f_typed(x["a"], x["b"], x["N"]), axis=1)
10 loops, best of 3: 20.3 ms per loop
-Now, we're talking! It's now over ten times faster than the original python
+Now, we're talking! It's now over ten times faster than the original Python
implementation, and we haven't *really* modified the code. Let's have another
look at what's eating up time:
diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst
index e8866daa9d99f..87ead5a1b80f0 100644
--- a/doc/source/user_guide/groupby.rst
+++ b/doc/source/user_guide/groupby.rst
@@ -672,7 +672,7 @@ accepts the special syntax in :meth:`GroupBy.agg`, known as "named aggregation",
)
-If your desired output column names are not valid python keywords, construct a dictionary
+If your desired output column names are not valid Python keywords, construct a dictionary
and unpack the keyword arguments
.. ipython:: python
@@ -1090,7 +1090,7 @@ will be passed into ``values``, and the group index will be passed into ``index`
.. warning::
When using ``engine='numba'``, there will be no "fall back" behavior internally. The group
- data and group index will be passed as numpy arrays to the JITed user defined function, and no
+ data and group index will be passed as NumPy arrays to the JITed user defined function, and no
alternative execution attempts will be tried.
.. note::
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 98c981539d207..2dd8f0cb212b1 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -55,7 +55,7 @@ of multi-axis indexing.
*label* of the index. This use is **not** an integer position along the
index.).
* A list or array of labels ``['a', 'b', 'c']``.
- * A slice object with labels ``'a':'f'`` (Note that contrary to usual python
+ * A slice object with labels ``'a':'f'`` (Note that contrary to usual Python
slices, **both** the start and the stop are included, when present in the
index! See :ref:`Slicing with labels <indexing.slicing_with_labels>`
and :ref:`Endpoints are inclusive <advanced.endpoints_are_inclusive>`.)
@@ -327,7 +327,7 @@ The ``.loc`` attribute is the primary access method. The following are valid inp
* A single label, e.g. ``5`` or ``'a'`` (Note that ``5`` is interpreted as a *label* of the index. This use is **not** an integer position along the index.).
* A list or array of labels ``['a', 'b', 'c']``.
-* A slice object with labels ``'a':'f'`` (Note that contrary to usual python
+* A slice object with labels ``'a':'f'`` (Note that contrary to usual Python
slices, **both** the start and the stop are included, when present in the
index! See :ref:`Slicing with labels <indexing.slicing_with_labels>`.
* A boolean array.
@@ -509,11 +509,11 @@ For getting a cross section using an integer position (equiv to ``df.xs(1)``):
df1.iloc[1]
-Out of range slice indexes are handled gracefully just as in Python/Numpy.
+Out of range slice indexes are handled gracefully just as in Python/NumPy.
.. ipython:: python
- # these are allowed in python/numpy.
+ # these are allowed in Python/NumPy.
x = list('abcdef')
x
x[4:10]
diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst
index d222297abc70b..c828bc28826b1 100644
--- a/doc/source/user_guide/options.rst
+++ b/doc/source/user_guide/options.rst
@@ -124,13 +124,13 @@ are restored automatically when you exit the ``with`` block:
Setting startup options in Python/IPython environment
-----------------------------------------------------
-Using startup scripts for the Python/IPython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default ipython profile can be found at:
+Using startup scripts for the Python/IPython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default IPython profile can be found at:
.. code-block:: none
$IPYTHONDIR/profile_default/startup
-More information can be found in the `ipython documentation
+More information can be found in the `IPython documentation
<https://ipython.org/ipython-doc/stable/interactive/tutorial.html#startup-files>`__. An example startup script for pandas is displayed below:
.. code-block:: python
@@ -332,7 +332,7 @@ display.large_repr truncate For DataFrames exceeding ma
(the behaviour in earlier versions of pandas).
allowable settings, ['truncate', 'info']
display.latex.repr False Whether to produce a latex DataFrame
- representation for jupyter frontends
+ representation for Jupyter frontends
that support it.
display.latex.escape True Escapes special characters in DataFrames, when
using the to_latex method.
@@ -413,7 +413,7 @@ display.show_dimensions truncate Whether to print out dimens
frame is truncated (e.g. not display
all rows and/or columns)
display.width 80 Width of the display in characters.
- In case python/IPython is running in
+ In case Python/IPython is running in
a terminal this can be set to None
and pandas will correctly auto-detect
the width. Note that the IPython notebook,
diff --git a/doc/source/user_guide/sparse.rst b/doc/source/user_guide/sparse.rst
index 3156e3088d860..e4eea57c43dbb 100644
--- a/doc/source/user_guide/sparse.rst
+++ b/doc/source/user_guide/sparse.rst
@@ -179,7 +179,7 @@ sparse values instead.
rather than a SparseSeries or SparseDataFrame.
This section provides some guidance on migrating your code to the new style. As a reminder,
-you can use the python warnings module to control warnings. But we recommend modifying
+you can use the Python warnings module to control warnings. But we recommend modifying
your code, rather than ignoring the warning.
**Construction**
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37808 | 2020-11-13T07:37:04Z | 2020-11-14T02:39:31Z | 2020-11-14T02:39:31Z | 2020-11-14T07:08:50Z |
Backport PR #37780 on branch 1.1.x (BUG: adding Timedelta to DatetimeIndex raising incorrectly) | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index a29ae1912e338..3b1f64e730830 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -14,7 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
--
+- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index c6945e2f78b5a..a10912aa45baa 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1253,7 +1253,7 @@ def _add_timedeltalike_scalar(self, other):
# adding a scalar preserves freq
new_freq = self.freq
- return type(self)(new_values, dtype=self.dtype, freq=new_freq)
+ return type(self)._simple_new(new_values, dtype=self.dtype, freq=new_freq)
def _add_timedelta_arraylike(self, other):
"""
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index 51841727d510b..7bf9455252d49 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -7,7 +7,7 @@
import pytest
import pandas as pd
-from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets
+from pandas import DatetimeIndex, Index, Timedelta, Timestamp, date_range, offsets
import pandas._testing as tm
@@ -408,3 +408,15 @@ def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
dtype="UInt32",
)
tm.assert_frame_equal(result, expected_data_frame)
+
+
+def test_add_timedelta_preserves_freq():
+ # GH#37295 should hold for any DTI with freq=None or Tick freq
+ tz = "Canada/Eastern"
+ dti = date_range(
+ start=Timestamp("2019-03-26 00:00:00-0400", tz=tz),
+ end=Timestamp("2020-10-17 00:00:00-0400", tz=tz),
+ freq="D",
+ )
+ result = dti + Timedelta(days=1)
+ assert result.freq == dti.freq
| Backport PR #37780: BUG: adding Timedelta to DatetimeIndex raising incorrectly | https://api.github.com/repos/pandas-dev/pandas/pulls/37806 | 2020-11-13T04:40:39Z | 2020-11-13T09:04:33Z | 2020-11-13T09:04:33Z | 2020-11-13T09:04:33Z |
BUG: skip_blank_lines ignored by read_fwf | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 09cb024cbd95c..dde977c4350df 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -517,6 +517,7 @@ I/O
- Bug in :meth:`DataFrame.to_hdf` was not dropping missing rows with ``dropna=True`` (:issue:`35719`)
- Bug in :func:`read_html` was raising a ``TypeError`` when supplying a ``pathlib.Path`` argument to the ``io`` parameter (:issue:`37705`)
- :meth:`to_excel` and :meth:`to_markdown` support writing to fsspec URLs such as S3 and Google Cloud Storage (:issue:`33987`)
+- Bug in :meth:`read_fw` was not skipping blank lines (even with ``skip_blank_lines=True``) (:issue:`37758`)
Plotting
^^^^^^^^
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index d7930f35a1421..ad5385cd659ef 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -3750,6 +3750,19 @@ def _make_reader(self, f):
self.infer_nrows,
)
+ def _remove_empty_lines(self, lines) -> List:
+ """
+ Returns the list of lines without the empty ones. With fixed-width
+ fields, empty lines become arrays of empty strings.
+
+ See PythonParser._remove_empty_lines.
+ """
+ return [
+ line
+ for line in lines
+ if any(not isinstance(e, str) or e.strip() for e in line)
+ ]
+
def _refine_defaults_read(
dialect: Union[str, csv.Dialect],
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index 4796cf0b79fae..5e9609956183b 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -340,6 +340,51 @@ def test_fwf_comment(comment):
tm.assert_almost_equal(result, expected)
+def test_fwf_skip_blank_lines():
+ data = """
+
+A B C D
+
+201158 360.242940 149.910199 11950.7
+201159 444.953632 166.985655 11788.4
+
+
+201162 502.953953 173.237159 12468.3
+
+"""
+ result = read_fwf(StringIO(data), skip_blank_lines=True)
+ expected = DataFrame(
+ [
+ [201158, 360.242940, 149.910199, 11950.7],
+ [201159, 444.953632, 166.985655, 11788.4],
+ [201162, 502.953953, 173.237159, 12468.3],
+ ],
+ columns=["A", "B", "C", "D"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ data = """\
+A B C D
+201158 360.242940 149.910199 11950.7
+201159 444.953632 166.985655 11788.4
+
+
+201162 502.953953 173.237159 12468.3
+"""
+ result = read_fwf(StringIO(data), skip_blank_lines=False)
+ expected = DataFrame(
+ [
+ [201158, 360.242940, 149.910199, 11950.7],
+ [201159, 444.953632, 166.985655, 11788.4],
+ [np.nan, np.nan, np.nan, np.nan],
+ [np.nan, np.nan, np.nan, np.nan],
+ [201162, 502.953953, 173.237159, 12468.3],
+ ],
+ columns=["A", "B", "C", "D"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
@pytest.mark.parametrize("thousands", [",", "#", "~"])
def test_fwf_thousands(thousands):
data = """\
| - [x] closes #37758
- [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/37803 | 2020-11-13T00:05:02Z | 2020-11-14T20:13:01Z | 2020-11-14T20:13:01Z | 2020-11-14T20:57:44Z |
REF: avoid try/except in Block.where | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 13e428c0419ec..3d5ed1bcb5759 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1442,34 +1442,21 @@ def where(
if not hasattr(cond, "shape"):
raise ValueError("where must have a condition that is ndarray like")
- def where_func(cond, values, other):
-
- if not (
- (self.is_integer or self.is_bool)
- and lib.is_float(other)
- and np.isnan(other)
- ):
- # np.where will cast integer array to floats in this case
- if not self._can_hold_element(other):
- raise TypeError
- if lib.is_scalar(other) and isinstance(values, np.ndarray):
- # convert datetime to datetime64, timedelta to timedelta64
- other = convert_scalar_for_putitemlike(other, values.dtype)
-
- # By the time we get here, we should have all Series/Index
- # args extracted to ndarray
- fastres = expressions.where(cond, values, other)
- return fastres
-
if cond.ravel("K").all():
result = values
else:
# see if we can operate on the entire block, or need item-by-item
# or if we are a single block (ndim == 1)
- try:
- result = where_func(cond, values, other)
- except TypeError:
-
+ if (
+ (self.is_integer or self.is_bool)
+ and lib.is_float(other)
+ and np.isnan(other)
+ ):
+ # GH#3733 special case to avoid object-dtype casting
+ # and go through numexpr path instead.
+ # In integer case, np.where will cast to floats
+ pass
+ elif not self._can_hold_element(other):
# we cannot coerce, return a compat dtype
# we are explicitly ignoring errors
block = self.coerce_to_target_dtype(other)
@@ -1478,6 +1465,18 @@ def where_func(cond, values, other):
)
return self._maybe_downcast(blocks, "infer")
+ if not (
+ (self.is_integer or self.is_bool)
+ and lib.is_float(other)
+ and np.isnan(other)
+ ):
+ # convert datetime to datetime64, timedelta to timedelta64
+ other = convert_scalar_for_putitemlike(other, values.dtype)
+
+ # By the time we get here, we should have all Series/Index
+ # args extracted to ndarray
+ result = expressions.where(cond, values, other)
+
if self._can_hold_na or self.ndim == 1:
if transpose:
| https://api.github.com/repos/pandas-dev/pandas/pulls/37802 | 2020-11-12T23:57:46Z | 2020-11-13T13:22:37Z | 2020-11-13T13:22:37Z | 2020-11-13T16:20:31Z | |
REGR: SeriesGroupBy where index has a tuple name fails | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index 3b1f64e730830..2a598c489e809 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
+- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/series.py b/pandas/core/series.py
index f243771ff97a5..800da18142825 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -900,7 +900,7 @@ def __getitem__(self, key):
return result
- except KeyError:
+ except (KeyError, TypeError):
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
# We still have the corner case where a tuple is a key
# in the first level of our MultiIndex
@@ -964,7 +964,7 @@ def _get_values_tuple(self, key):
return result
if not isinstance(self.index, MultiIndex):
- raise ValueError("key of type tuple not found and not a MultiIndex")
+ raise KeyError("key of type tuple not found and not a MultiIndex")
# If key is contained, would have returned by now
indexer, new_index = self.index.get_loc_level(key)
@@ -1020,7 +1020,7 @@ def __setitem__(self, key, value):
except TypeError as err:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex):
- raise ValueError(
+ raise KeyError(
"key of type tuple not found and not a MultiIndex"
) from err
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 3a4abd58f0d39..cd1fc67772849 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2146,3 +2146,13 @@ def test_groupby_duplicate_columns():
result = df.groupby([0, 0, 0, 0]).min()
expected = DataFrame([["e", "a", 1]], columns=["A", "B", "B"])
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_series_with_tuple_name():
+ # GH 37755
+ ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a"))
+ ser.index.name = ("b", "b")
+ result = ser.groupby(level=0).last()
+ expected = Series([2, 4], index=[1, 2], name=("a", "a"))
+ expected.index.name = ("b", "b")
+ tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 1f2adaafbbccd..682c057f05700 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -327,9 +327,9 @@ def test_loc_setitem_2d_to_1d_raises():
def test_basic_getitem_setitem_corner(datetime_series):
# invalid tuples, e.g. td.ts[:, None] vs. td.ts[:, 2]
msg = "key of type tuple not found and not a MultiIndex"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(KeyError, match=msg):
datetime_series[:, 2]
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(KeyError, match=msg):
datetime_series[:, 2] = 2
# weird lists. [slice(0, 5)] will work but not two slices
| - [x] closes #37755
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
The groupby code that calls `Series.__getitem__` catches `KeyError` and `TypeError`. If a tuple is fed into an `Index` that is not a `MultiIndex`, we were raising a `ValueError` but `KeyError` seems more appropriate here and also fixes the regression.
While working on this, I found that we raise a `KeyError` inappropriately if an index of tuples contains duplicates, however this exists back in 1.0.x and so is not part of the regression. I've opened #37800 for this. | https://api.github.com/repos/pandas-dev/pandas/pulls/37801 | 2020-11-12T23:52:40Z | 2020-11-14T03:31:47Z | 2020-11-14T03:31:46Z | 2020-11-24T16:55:15Z |
BUG: DataFrame.all(bool_only=True) inconsistency with object dtype | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 09cb024cbd95c..4dedf9771955d 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -236,6 +236,54 @@ Other enhancements
- Improve numerical stability for :meth:`Rolling.skew()`, :meth:`Rolling.kurt()`, :meth:`Expanding.skew()` and :meth:`Expanding.kurt()` through implementation of Kahan summation (:issue:`6929`)
- Improved error reporting for subsetting columns of a :class:`DataFrameGroupBy` with ``axis=1`` (:issue:`37725`)
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_120.notable_bug_fixes:
+
+Notable bug fixes
+~~~~~~~~~~~~~~~~~
+
+These are bug fixes that might have notable behavior changes.
+
+Consistency of DataFrame Reductions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+:meth:`DataFrame.any` and :meth:`DataFrame.all` with ``bool_only=True`` now
+determines whether to exclude object-dtype columns on a column-by-column basis,
+instead of checking if *all* object-dtype columns can be considered boolean.
+
+This prevents pathological behavior where applying the reduction on a subset
+of columns could result in a larger :class:`Series` result. See (:issue:`37799`).
+
+.. ipython:: python
+
+ df = pd.DataFrame({"A": ["foo", "bar"], "B": [True, False]}, dtype=object)
+ df["C"] = pd.Series([True, True])
+
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [5]: df.all(bool_only=True)
+ Out[5]:
+ C True
+ dtype: bool
+
+ In [6]: df[["B", "C"]].all(bool_only=True)
+ Out[6]:
+ B False
+ C True
+ dtype: bool
+
+*New behavior*:
+
+.. ipython:: python
+
+ In [5]: df.all(bool_only=True)
+
+ In [6]: df[["B", "C"]].all(bool_only=True)
+
+
.. _whatsnew_120.api_breaking.python:
Increased minimum version for Python
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index aa19c599e5898..92f6bb6f1cbdd 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -450,6 +450,20 @@ def f(mask, val, idx):
return self.split_and_operate(None, f, inplace)
+ def _split(self) -> List["Block"]:
+ """
+ Split a block into a list of single-column blocks.
+ """
+ assert self.ndim == 2
+
+ new_blocks = []
+ for i, ref_loc in enumerate(self.mgr_locs):
+ vals = self.values[slice(i, i + 1)]
+
+ nb = self.make_block(vals, [ref_loc])
+ new_blocks.append(nb)
+ return new_blocks
+
def split_and_operate(self, mask, f, inplace: bool) -> List["Block"]:
"""
split the block per-column, and apply the callable f
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 767c653f8a404..155d88d6ec2d9 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -713,13 +713,28 @@ def is_view(self) -> bool:
def get_bool_data(self, copy: bool = False) -> "BlockManager":
"""
+ Select blocks that are bool-dtype and columns from object-dtype blocks
+ that are all-bool.
+
Parameters
----------
copy : bool, default False
Whether to copy the blocks
"""
- self._consolidate_inplace()
- return self._combine([b for b in self.blocks if b.is_bool], copy)
+
+ new_blocks = []
+
+ for blk in self.blocks:
+ if blk.dtype == bool:
+ new_blocks.append(blk)
+
+ elif blk.is_object:
+ nbs = blk._split()
+ for nb in nbs:
+ if nb.is_bool:
+ new_blocks.append(nb)
+
+ return self._combine(new_blocks, copy)
def get_numeric_data(self, copy: bool = False) -> "BlockManager":
"""
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 374d185f45844..95cb770a11408 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1118,6 +1118,37 @@ def test_any_all_object(self):
result = np.any(DataFrame(columns=["a", "b"])).item()
assert result is False
+ def test_any_all_object_bool_only(self):
+ df = DataFrame({"A": ["foo", 2], "B": [True, False]}).astype(object)
+ df._consolidate_inplace()
+ df["C"] = Series([True, True])
+
+ # The underlying bug is in DataFrame._get_bool_data, so we check
+ # that while we're here
+ res = df._get_bool_data()
+ expected = df[["B", "C"]]
+ tm.assert_frame_equal(res, expected)
+
+ res = df.all(bool_only=True, axis=0)
+ expected = Series([False, True], index=["B", "C"])
+ tm.assert_series_equal(res, expected)
+
+ # operating on a subset of columns should not produce a _larger_ Series
+ res = df[["B", "C"]].all(bool_only=True, axis=0)
+ tm.assert_series_equal(res, expected)
+
+ assert not df.all(bool_only=True, axis=None)
+
+ res = df.any(bool_only=True, axis=0)
+ expected = Series([True, True], index=["B", "C"])
+ tm.assert_series_equal(res, expected)
+
+ # operating on a subset of columns should not produce a _larger_ Series
+ res = df[["B", "C"]].any(bool_only=True, axis=0)
+ tm.assert_series_equal(res, expected)
+
+ assert df.any(bool_only=True, axis=None)
+
@pytest.mark.parametrize("method", ["any", "all"])
def test_any_all_level_axis_none_raises(self, method):
df = DataFrame(
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 88b91ecc79060..d069b5aa08e22 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -264,6 +264,25 @@ def test_delete(self):
with pytest.raises(IndexError, match=None):
newb.delete(3)
+ def test_split(self):
+ # GH#37799
+ values = np.random.randn(3, 4)
+ blk = make_block(values, placement=[3, 1, 6])
+ result = blk._split()
+
+ # check that we get views, not copies
+ values[:] = -9999
+ assert (blk.values == -9999).all()
+
+ assert len(result) == 3
+ expected = [
+ make_block(values[[0]], placement=[3]),
+ make_block(values[[1]], placement=[1]),
+ make_block(values[[2]], placement=[6]),
+ ]
+ for res, exp in zip(result, expected):
+ assert_block_equal(res, exp)
+
class TestBlockManager:
def test_attrs(self):
@@ -667,7 +686,7 @@ def test_get_bool_data(self):
mgr.iset(6, np.array([True, False, True], dtype=np.object_))
bools = mgr.get_bool_data()
- tm.assert_index_equal(bools.items, Index(["bool"]))
+ tm.assert_index_equal(bools.items, Index(["bool", "dt"]))
tm.assert_almost_equal(
mgr.iget(mgr.items.get_loc("bool")).internal_values(),
bools.iget(bools.items.get_loc("bool")).internal_values(),
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Discussed on the dev call yesterday. | https://api.github.com/repos/pandas-dev/pandas/pulls/37799 | 2020-11-12T23:52:01Z | 2020-11-14T02:24:11Z | 2020-11-14T02:24:11Z | 2020-11-14T04:05:53Z |
TYP: fix mypy ignored error in pandas/tests/io/test_fsspec.py | diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py
index 666da677d702e..f8081a6a69e83 100644
--- a/pandas/tests/io/test_fsspec.py
+++ b/pandas/tests/io/test_fsspec.py
@@ -24,10 +24,7 @@
"dt": date_range("2018-06-18", periods=2),
}
)
-# the ignore on the following line accounts for to_csv returning Optional(str)
-# in general, but always str in the case we give no filename
-# error: Item "None" of "Optional[str]" has no attribute "encode"
-text = df1.to_csv(index=False).encode() # type: ignore[union-attr]
+text = str(df1.to_csv(index=False)).encode()
@pytest.fixture
| - [ ] xref #37715
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Handle mypy ignored error in pandas/tests/io/test_fsspec.py
Is this decision correct? | https://api.github.com/repos/pandas-dev/pandas/pulls/37797 | 2020-11-12T23:01:09Z | 2020-11-13T04:30:00Z | 2020-11-13T04:30:00Z | 2023-04-18T04:19:21Z |
[BUG]: Fix bug in MultiIndex.drop dropped nan when non existing key was given | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index f751a91cecf19..650478322068b 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -483,6 +483,7 @@ MultiIndex
- Bug in :meth:`DataFrame.xs` when used with :class:`IndexSlice` raises ``TypeError`` with message ``"Expected label or tuple of labels"`` (:issue:`35301`)
- Bug in :meth:`DataFrame.reset_index` with ``NaT`` values in index raises ``ValueError`` with message ``"cannot convert float NaN to integer"`` (:issue:`36541`)
- Bug in :meth:`DataFrame.combine_first` when used with :class:`MultiIndex` containing string and ``NaN`` values raises ``TypeError`` (:issue:`36562`)
+- Bug in :meth:`MultiIndex.drop` dropped ``NaN`` values when non existing key was given as input (:issue:`18853`)
I/O
^^^
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 5a3f2b0853c4f..7904d7aaecdbd 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2156,6 +2156,10 @@ def _drop_from_level(self, codes, level, errors="raise"):
i = self._get_level_number(level)
index = self.levels[i]
values = index.get_indexer(codes)
+ # If nan should be dropped it will equal -1 here. We have to check which values
+ # are not nan and equal -1, this means they are missing in the index
+ nan_codes = isna(codes)
+ values[(np.equal(nan_codes, False)) & (values == -1)] = -2
mask = ~algos.isin(self.codes[i], values)
if mask.all() and errors != "ignore":
diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py
index 6ba565f0406ab..06019ed0a8b14 100644
--- a/pandas/tests/indexes/multi/test_drop.py
+++ b/pandas/tests/indexes/multi/test_drop.py
@@ -139,3 +139,11 @@ def test_drop_not_lexsorted():
tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi)
with tm.assert_produces_warning(PerformanceWarning):
tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a"))
+
+
+def test_drop_with_nan_in_index(nulls_fixture):
+ # GH#18853
+ mi = MultiIndex.from_tuples([("blah", nulls_fixture)], names=["name", "date"])
+ msg = r"labels \[Timestamp\('2001-01-01 00:00:00'\)\] not found in level"
+ with pytest.raises(KeyError, match=msg):
+ mi.drop(pd.Timestamp("2001"), level="date")
| - [x] closes #18853
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Additional question:
The doc says (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.drop.html) that ``drop`` raises when not all labels are found, but
```
pd.DataFrame(index=pd.MultiIndex.from_product([range(3), range(3)])).drop([1, 5], level=0)
```
does not raise, because ``1`` is found. Should we implement, that it raises every time when at least one of the keys is not found? | https://api.github.com/repos/pandas-dev/pandas/pulls/37794 | 2020-11-12T21:39:08Z | 2020-11-18T18:35:06Z | 2020-11-18T18:35:06Z | 2020-11-18T20:37:25Z |
Remove unnecessary casts in tokenizer.c | diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index df8ec68986ccb..88144330c1fe9 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -159,7 +159,7 @@ int parser_init(parser_t *self) {
self->warn_msg = NULL;
// token stream
- self->stream = (char *)malloc(STREAM_INIT_SIZE * sizeof(char));
+ self->stream = malloc(STREAM_INIT_SIZE * sizeof(char));
if (self->stream == NULL) {
parser_cleanup(self);
return PARSER_OUT_OF_MEMORY;
@@ -170,16 +170,16 @@ int parser_init(parser_t *self) {
// word pointers and metadata
sz = STREAM_INIT_SIZE / 10;
sz = sz ? sz : 1;
- self->words = (char **)malloc(sz * sizeof(char *));
- self->word_starts = (int64_t *)malloc(sz * sizeof(int64_t));
+ self->words = malloc(sz * sizeof(char *));
+ self->word_starts = malloc(sz * sizeof(int64_t));
self->max_words_cap = sz;
self->words_cap = sz;
self->words_len = 0;
// line pointers and metadata
- self->line_start = (int64_t *)malloc(sz * sizeof(int64_t));
+ self->line_start = malloc(sz * sizeof(int64_t));
- self->line_fields = (int64_t *)malloc(sz * sizeof(int64_t));
+ self->line_fields = malloc(sz * sizeof(int64_t));
self->lines_cap = sz;
self->lines = 0;
@@ -345,7 +345,7 @@ static int push_char(parser_t *self, char c) {
"self->stream_cap(%d)\n",
self->stream_len, self->stream_cap))
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize,
"Buffer overflow caught - possible malformed input file.\n");
return PARSER_OUT_OF_MEMORY;
@@ -362,7 +362,7 @@ int PANDAS_INLINE end_field(parser_t *self) {
"self->words_cap(%zu)\n",
self->words_len, self->words_cap))
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize,
"Buffer overflow caught - possible malformed input file.\n");
return PARSER_OUT_OF_MEMORY;
@@ -398,7 +398,7 @@ static void append_warning(parser_t *self, const char *msg) {
void *newptr;
if (self->warn_msg == NULL) {
- self->warn_msg = (char *)malloc(length + 1);
+ self->warn_msg = malloc(length + 1);
snprintf(self->warn_msg, length + 1, "%s", msg);
} else {
ex_length = strlen(self->warn_msg);
@@ -459,10 +459,10 @@ static int end_line(parser_t *self) {
// file_lines is now the actual file line number (starting at 1)
if (self->error_bad_lines) {
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize,
- "Expected %d fields in line %lld, saw %lld\n",
- ex_fields, (long long)self->file_lines, (long long)fields);
+ "Expected %d fields in line %" PRIu64 ", saw %" PRId64 "\n",
+ ex_fields, self->file_lines, fields);
TRACE(("Error at line %d, %d fields\n", self->file_lines, fields));
@@ -471,11 +471,10 @@ static int end_line(parser_t *self) {
// simply skip bad lines
if (self->warn_bad_lines) {
// pass up error message
- msg = (char *)malloc(bufsize);
+ msg = malloc(bufsize);
snprintf(msg, bufsize,
- "Skipping line %lld: expected %d fields, saw %lld\n",
- (long long)self->file_lines, ex_fields,
- (long long)fields);
+ "Skipping line %" PRIu64 ": expected %d fields, saw %"
+ PRId64 "\n", self->file_lines, ex_fields, fields);
append_warning(self, msg);
free(msg);
}
@@ -487,7 +486,7 @@ static int end_line(parser_t *self) {
// might overrun the buffer when closing fields
if (make_stream_space(self, ex_fields - fields) < 0) {
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize, "out of memory");
return -1;
}
@@ -508,7 +507,7 @@ static int end_line(parser_t *self) {
"end_line: ERROR!!! self->lines(%zu) >= self->lines_cap(%zu)\n",
self->lines, self->lines_cap))
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize,
"Buffer overflow caught - "
"possible malformed input file.\n");
@@ -569,7 +568,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes) {
if (status != REACHED_EOF && self->data == NULL) {
int64_t bufsize = 200;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
if (status == CALLING_READ_FAILED) {
snprintf(self->error_msg, bufsize,
@@ -600,7 +599,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes) {
TRACE(("PUSH_CHAR: ERROR!!! slen(%d) >= stream_cap(%d)\n", slen, \
self->stream_cap)) \
int64_t bufsize = 100; \
- self->error_msg = (char *)malloc(bufsize); \
+ self->error_msg = malloc(bufsize); \
snprintf(self->error_msg, bufsize, \
"Buffer overflow caught - possible malformed input file.\n");\
return PARSER_OUT_OF_MEMORY; \
@@ -730,7 +729,7 @@ int tokenize_bytes(parser_t *self,
if (make_stream_space(self, self->datalen - self->datapos) < 0) {
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize, "out of memory");
return -1;
}
@@ -1037,7 +1036,7 @@ int tokenize_bytes(parser_t *self,
self->state = IN_FIELD;
} else {
int64_t bufsize = 100;
- self->error_msg = (char *)malloc(bufsize);
+ self->error_msg = malloc(bufsize);
snprintf(self->error_msg, bufsize,
"delimiter expected after quote in quote");
goto parsingerror;
@@ -1150,8 +1149,8 @@ static int parser_handle_eof(parser_t *self) {
case IN_QUOTED_FIELD:
self->error_msg = (char *)malloc(bufsize);
snprintf(self->error_msg, bufsize,
- "EOF inside string starting at row %lld",
- (long long)self->file_lines);
+ "EOF inside string starting at row %" PRIu64,
+ self->file_lines);
return -1;
case ESCAPED_CHAR:
@@ -1203,7 +1202,7 @@ int parser_consume_rows(parser_t *self, size_t nrows) {
/* move stream, only if something to move */
if (char_count < self->stream_len) {
- memmove((void *)self->stream, (void *)(self->stream + char_count),
+ memmove(self->stream, (self->stream + char_count),
self->stream_len - char_count);
}
/* buffer counts */
@@ -1269,20 +1268,16 @@ int parser_trim_buffers(parser_t *self) {
new_cap = _next_pow2(self->words_len) + 1;
if (new_cap < self->words_cap) {
TRACE(("parser_trim_buffers: new_cap < self->words_cap\n"));
- newptr = realloc((void *)self->words, new_cap * sizeof(char *));
- if (newptr == NULL) {
+ self->words = realloc(self->words, new_cap * sizeof(char *));
+ if (self->words == NULL) {
return PARSER_OUT_OF_MEMORY;
- } else {
- self->words = (char **)newptr;
}
- newptr = realloc((void *)self->word_starts,
- new_cap * sizeof(int64_t));
- if (newptr == NULL) {
+ self->word_starts = realloc(self->word_starts,
+ new_cap * sizeof(int64_t));
+ if (self->word_starts == NULL) {
return PARSER_OUT_OF_MEMORY;
- } else {
- self->word_starts = (int64_t *)newptr;
- self->words_cap = new_cap;
}
+ self->words_cap = new_cap;
}
/* trim stream */
@@ -1295,7 +1290,7 @@ int parser_trim_buffers(parser_t *self) {
TRACE(
("parser_trim_buffers: new_cap < self->stream_cap, calling "
"realloc\n"));
- newptr = realloc((void *)self->stream, new_cap);
+ newptr = realloc(self->stream, new_cap);
if (newptr == NULL) {
return PARSER_OUT_OF_MEMORY;
} else {
@@ -1321,19 +1316,19 @@ int parser_trim_buffers(parser_t *self) {
new_cap = _next_pow2(self->lines) + 1;
if (new_cap < self->lines_cap) {
TRACE(("parser_trim_buffers: new_cap < self->lines_cap\n"));
- newptr = realloc((void *)self->line_start,
+ newptr = realloc(self->line_start,
new_cap * sizeof(int64_t));
if (newptr == NULL) {
return PARSER_OUT_OF_MEMORY;
} else {
- self->line_start = (int64_t *)newptr;
+ self->line_start = newptr;
}
- newptr = realloc((void *)self->line_fields,
+ newptr = realloc(self->line_fields,
new_cap * sizeof(int64_t));
if (newptr == NULL) {
return PARSER_OUT_OF_MEMORY;
} else {
- self->line_fields = (int64_t *)newptr;
+ self->line_fields = newptr;
self->lines_cap = new_cap;
}
}
@@ -1828,14 +1823,14 @@ double round_trip(const char *p, char **q, char decimal, char sci, char tsep,
if (endpc == pc + strlen(pc)) {
if (q != NULL) {
// report endptr from source string (p)
- *q = (char *) endptr;
+ *q = endptr;
}
} else {
*error = -1;
if (q != NULL) {
// p and pc are different len due to tsep removal. Can't report
// how much it has consumed of p. Just rewind to beginning.
- *q = (char *)p;
+ *q = (char *)p; // TODO(willayd): this could be undefined behavior
}
}
if (maybe_int != NULL) *maybe_int = 0;
@@ -1863,7 +1858,7 @@ int uint64_conflict(uint_state *self) {
int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max,
int *error, char tsep) {
- const char *p = (const char *)p_item;
+ const char *p = p_item;
int isneg = 0;
int64_t number = 0;
int d;
@@ -1983,7 +1978,7 @@ int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max,
uint64_t str_to_uint64(uint_state *state, const char *p_item, int64_t int_max,
uint64_t uint_max, int *error, char tsep) {
- const char *p = (const char *)p_item;
+ const char *p = p_item;
uint64_t pre_max = uint_max / 10;
int dig_pre_max = uint_max % 10;
uint64_t number = 0;
| Some of these are visual clutter, some are actual bugs though in unlikely cases (see the format specifiers)
https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
| https://api.github.com/repos/pandas-dev/pandas/pulls/37792 | 2020-11-12T19:47:21Z | 2020-11-13T13:20:13Z | 2020-11-13T13:20:13Z | 2023-04-12T20:17:00Z |
CLN: remove unreachable in interpolate_with_fill | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ed77a210b6913..0d56fe2411308 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1251,7 +1251,6 @@ def interpolate(
axis=axis,
inplace=inplace,
limit=limit,
- coerce=coerce,
downcast=downcast,
)
# validate the interp method
@@ -1278,20 +1277,12 @@ def _interpolate_with_fill(
axis: int = 0,
inplace: bool = False,
limit: Optional[int] = None,
- coerce: bool = False,
downcast: Optional[str] = None,
) -> List["Block"]:
""" fillna but using the interpolate machinery """
inplace = validate_bool_kwarg(inplace, "inplace")
- # if we are coercing, then don't force the conversion
- # if the block can't hold the type
- if coerce:
- if not self._can_hold_na:
- if inplace:
- return [self]
- else:
- return [self.copy()]
+ assert self._can_hold_na # checked by caller
values = self.values if inplace else self.values.copy()
| https://api.github.com/repos/pandas-dev/pandas/pulls/37791 | 2020-11-12T19:46:33Z | 2020-11-13T04:18:10Z | 2020-11-13T04:18:10Z | 2020-11-13T04:28:23Z | |
CLN: remove no-longer-reachable Block.replace code | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ed77a210b6913..a1b725cbc13ab 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -735,40 +735,12 @@ def replace(
inplace = validate_bool_kwarg(inplace, "inplace")
original_to_replace = to_replace
- # If we cannot replace with own dtype, convert to ObjectBlock and
- # retry
if not self._can_hold_element(to_replace):
- if not isinstance(to_replace, list):
- if inplace:
- return [self]
- return [self.copy()]
-
- to_replace = [x for x in to_replace if self._can_hold_element(x)]
- if not len(to_replace):
- # GH#28084 avoid costly checks since we can infer
- # that there is nothing to replace in this block
- if inplace:
- return [self]
- return [self.copy()]
-
- if len(to_replace) == 1:
- # _can_hold_element checks have reduced this back to the
- # scalar case and we can avoid a costly object cast
- return self.replace(to_replace[0], value, inplace=inplace, regex=regex)
-
- # GH 22083, TypeError or ValueError occurred within error handling
- # causes infinite loop. Cast and retry only if not objectblock.
- if is_object_dtype(self):
- raise AssertionError
-
- # try again with a compatible block
- block = self.astype(object)
- return block.replace(
- to_replace=to_replace,
- value=value,
- inplace=inplace,
- regex=regex,
- )
+ # We cannot hold `to_replace`, so we know immediately that
+ # replacing it is a no-op.
+ # Note: If to_replace were a list, NDFrame.replace would call
+ # replace_list instead of replace.
+ return [self] if inplace else [self.copy()]
values = self.values
if lib.is_scalar(to_replace) and isinstance(values, np.ndarray):
| We recently changed NDFrame.replace such that Block.replace never gets a list for `to_replace`, so this chunk of code is never reachable. | https://api.github.com/repos/pandas-dev/pandas/pulls/37789 | 2020-11-12T19:00:19Z | 2020-11-13T04:18:42Z | 2020-11-13T04:18:42Z | 2020-11-13T04:29:31Z |
REF: implement Block._putmask_simple for non-casting putmask | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ed77a210b6913..769243ce4448a 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -417,6 +417,7 @@ def fillna(
inplace = validate_bool_kwarg(inplace, "inplace")
mask = isna(self.values)
+ mask = _extract_bool_array(mask)
if limit is not None:
limit = libalgos.validate_limit(None, limit=limit)
mask[mask.cumsum(self.ndim - 1) > limit] = False
@@ -428,9 +429,10 @@ def fillna(
return [self.copy()]
if self._can_hold_element(value):
- # equivalent: _try_coerce_args(value) would not raise
- blocks = self.putmask(mask, value, inplace=inplace)
- return self._maybe_downcast(blocks, downcast)
+ nb = self if inplace else self.copy()
+ nb._putmask_simple(mask, value)
+ # TODO: should be nb._maybe_downcast?
+ return self._maybe_downcast([nb], downcast)
# we can't process the value, but nothing to do
if not mask.any():
@@ -886,6 +888,7 @@ def comp(s: Scalar, mask: np.ndarray, regex: bool = False) -> np.ndarray:
mask = ~isna(self.values)
masks = [comp(s, mask, regex) for s in src_list]
+ masks = [_extract_bool_array(x) for x in masks]
rb = [self if inplace else self.copy()]
for i, (src, dest) in enumerate(zip(src_list, dest_list)):
@@ -1024,6 +1027,30 @@ def setitem(self, indexer, value):
block = self.make_block(values)
return block
+ def _putmask_simple(self, mask: np.ndarray, value: Any):
+ """
+ Like putmask but
+
+ a) we do not cast on failure
+ b) we do not handle repeating or truncating like numpy.
+
+ Parameters
+ ----------
+ mask : np.ndarray[bool]
+ We assume _extract_bool_array has already been called.
+ value : Any
+ We assume self._can_hold_element(value)
+ """
+ values = self.values
+
+ if lib.is_scalar(value) and isinstance(values, np.ndarray):
+ value = convert_scalar_for_putitemlike(value, values.dtype)
+
+ if is_list_like(value) and len(value) == len(values):
+ values[mask] = value[mask]
+ else:
+ values[mask] = value
+
def putmask(
self, mask, new, inplace: bool = False, axis: int = 0, transpose: bool = False
) -> List["Block"]:
@@ -1628,8 +1655,11 @@ def _replace_coerce(
"""
if mask.any():
if not regex:
- self = self.coerce_to_target_dtype(value)
- return self.putmask(mask, value, inplace=inplace)
+ nb = self.coerce_to_target_dtype(value)
+ if nb is self and not inplace:
+ nb = nb.copy()
+ nb._putmask_simple(mask, value)
+ return [nb]
else:
regex = _should_use_regex(regex, to_replace)
if regex:
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index baa310ddd6f09..9011136e12afb 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -709,19 +709,25 @@ def test_replace_list(self):
)
tm.assert_frame_equal(res, expec)
- def test_replace_with_empty_list(self):
+ def test_replace_with_empty_list(self, frame_or_series):
# GH 21977
- s = Series([["a", "b"], [], np.nan, [1]])
- df = DataFrame({"col": s})
- expected = df
- result = df.replace([], np.nan)
- tm.assert_frame_equal(result, expected)
+ ser = Series([["a", "b"], [], np.nan, [1]])
+ obj = DataFrame({"col": ser})
+ if frame_or_series is Series:
+ obj = ser
+ expected = obj
+ result = obj.replace([], np.nan)
+ tm.assert_equal(result, expected)
# GH 19266
- with pytest.raises(ValueError, match="cannot assign mismatch"):
- df.replace({np.nan: []})
- with pytest.raises(ValueError, match="cannot assign mismatch"):
- df.replace({np.nan: ["dummy", "alt"]})
+ msg = (
+ "NumPy boolean array indexing assignment cannot assign {size} "
+ "input values to the 1 output values where the mask is true"
+ )
+ with pytest.raises(ValueError, match=msg.format(size=0)):
+ obj.replace({np.nan: []})
+ with pytest.raises(ValueError, match=msg.format(size=2)):
+ obj.replace({np.nan: ["dummy", "alt"]})
def test_replace_series_dict(self):
# from GH 3064
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index 79d6fc22aba97..27cf15b4e187b 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -143,19 +143,6 @@ def test_replace_with_single_list(self):
assert return_value is None
tm.assert_series_equal(s, ser)
- def test_replace_with_empty_list(self):
- # GH 21977
- s = pd.Series([[1], [2, 3], [], np.nan, [4]])
- expected = s
- result = s.replace([], np.nan)
- tm.assert_series_equal(result, expected)
-
- # GH 19266
- with pytest.raises(ValueError, match="cannot assign mismatch"):
- s.replace({np.nan: []})
- with pytest.raises(ValueError, match="cannot assign mismatch"):
- s.replace({np.nan: ["dummy", "alt"]})
-
def test_replace_mixed_types(self):
s = pd.Series(np.arange(5), dtype="int64")
| Much easier to reason about than Block.putmask. | https://api.github.com/repos/pandas-dev/pandas/pulls/37788 | 2020-11-12T16:19:01Z | 2020-11-13T04:19:52Z | 2020-11-13T04:19:52Z | 2020-11-13T04:30:26Z |
Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index 2a598c489e809..323342cb43950 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
+- Fixed regression in :meth:`DataFrame.loc` and :meth:`Series.loc` for ``__setitem__`` when one-dimensional tuple was given to select from :class:`MultiIndex` (:issue:`37711`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index c5e331a104726..e0bf43d3a0140 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -650,9 +650,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None):
if self.ndim != 2:
return
- if isinstance(key, tuple):
+ if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex):
# key may be a tuple if we are .loc
- # in that case, set key to the column part of key
+ # if index is not a MultiIndex, set key to column part
key = key[column_axis]
axis = column_axis
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 646520a9ac54f..165d34180dfab 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -288,6 +288,23 @@ def convert_nested_indexer(indexer_type, keys):
tm.assert_series_equal(result, expected)
+ def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series):
+ # GH#37711
+ mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
+ obj = frame_or_series([1, 2], index=mi)
+ obj.loc[("a",)] = 0
+ expected = frame_or_series([0, 2], index=mi)
+ tm.assert_equal(obj, expected)
+
+ @pytest.mark.parametrize("indexer", [("a",), ("a")])
+ def test_multiindex_one_dimensional_tuple_columns(self, indexer):
+ # GH#37711
+ mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
+ obj = DataFrame([1, 2], index=mi)
+ obj.loc[indexer, :] = 0
+ expected = DataFrame([0, 2], index=mi)
+ tm.assert_frame_equal(obj, expected)
+
@pytest.mark.parametrize(
"indexer, pos",
| - [x] closes #37711
- [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/37787 | 2020-11-12T13:06:14Z | 2020-11-14T16:51:58Z | 2020-11-14T16:51:58Z | 2020-11-14T19:06:11Z |
CI/TST: use https to avoid ResourceWarning in html tests | diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index eb704ccf1e594..9a883aac69e6b 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -123,7 +123,7 @@ def test_to_html_compat(self):
@tm.network
def test_banklist_url_positional_match(self):
- url = "http://www.fdic.gov/bank/individual/failed/banklist.html"
+ url = "https://www.fdic.gov/bank/individual/failed/banklist.html"
# Passing match argument as positional should cause a FutureWarning.
with tm.assert_produces_warning(FutureWarning):
df1 = self.read_html(
@@ -136,7 +136,7 @@ def test_banklist_url_positional_match(self):
@tm.network
def test_banklist_url(self):
- url = "http://www.fdic.gov/bank/individual/failed/banklist.html"
+ url = "https://www.fdic.gov/bank/individual/failed/banklist.html"
df1 = self.read_html(
url, match="First Federal Bank of Florida", attrs={"id": "table"}
)
| See #36467
(no idea if this would actually fix anything, just mimicking what @alimcmaster1 did in https://github.com/pandas-dev/pandas/pull/36480) | https://api.github.com/repos/pandas-dev/pandas/pulls/37786 | 2020-11-12T12:00:25Z | 2020-11-13T15:24:25Z | 2020-11-13T15:24:25Z | 2020-11-13T16:31:05Z |
REF: simplify Block.replace | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 0d3912847dca0..e9b6d53a095d3 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -580,6 +580,7 @@ Other
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`)
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` with numeric values and string ``to_replace`` (:issue:`34789`)
+- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly casting from ``PeriodDtype`` to object dtype (:issue:`34871`)
- Fixed bug in metadata propagation incorrectly copying DataFrame columns as metadata when the column name overlaps with the metadata name (:issue:`37037`)
- Fixed metadata propagation in the :class:`Series.dt`, :class:`Series.str` accessors, :class:`DataFrame.duplicated`, :class:`DataFrame.stack`, :class:`DataFrame.unstack`, :class:`DataFrame.pivot`, :class:`DataFrame.append`, :class:`DataFrame.diff`, :class:`DataFrame.applymap` and :class:`DataFrame.update` methods (:issue:`28283`) (:issue:`37381`)
- Bug in :meth:`Index.union` behaving differently depending on whether operand is a :class:`Index` or other list-like (:issue:`36384`)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 13e428c0419ec..c20afb06cc1a2 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -752,36 +752,21 @@ def replace(
to_replace = convert_scalar_for_putitemlike(to_replace, values.dtype)
mask = missing.mask_missing(values, to_replace)
+ if not mask.any():
+ # Note: we get here with test_replace_extension_other incorrectly
+ # bc _can_hold_element is incorrect.
+ return [self] if inplace else [self.copy()]
- try:
- blocks = self.putmask(mask, value, inplace=inplace)
- # Note: it is _not_ the case that self._can_hold_element(value)
- # is always true at this point. In particular, that can fail
- # for:
- # "2u" with bool-dtype, float-dtype
- # 0.5 with int64-dtype
- # np.nan with int64-dtype
- except (TypeError, ValueError):
- # GH 22083, TypeError or ValueError occurred within error handling
- # causes infinite loop. Cast and retry only if not objectblock.
- if is_object_dtype(self):
- raise
-
- if not self.is_extension:
- # TODO: https://github.com/pandas-dev/pandas/issues/32586
- # Need an ExtensionArray._can_hold_element to indicate whether
- # a scalar value can be placed in the array.
- assert not self._can_hold_element(value), value
-
- # try again with a compatible block
- block = self.astype(object)
- return block.replace(
+ if not self._can_hold_element(value):
+ blk = self.astype(object)
+ return blk.replace(
to_replace=original_to_replace,
value=value,
- inplace=inplace,
+ inplace=True,
regex=regex,
)
+ blocks = self.putmask(mask, value, inplace=inplace)
blocks = extend_blocks(
[b.convert(numeric=False, copy=not inplace) for b in blocks]
)
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index 9011136e12afb..8f3dcc96ddc3d 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -1523,18 +1523,18 @@ def test_replace_with_duplicate_columns(self, replacement):
tm.assert_frame_equal(result, expected)
- @pytest.mark.xfail(
- reason="replace() changes dtype from period to object, see GH34871", strict=True
- )
- def test_replace_period_ignore_float(self):
+ def test_replace_period_ignore_float(self, frame_or_series):
"""
Regression test for GH#34871: if df.replace(1.0, 0.0) is called on a df
with a Period column the old, faulty behavior is to raise TypeError.
"""
- df = DataFrame({"Per": [pd.Period("2020-01")] * 3})
- result = df.replace(1.0, 0.0)
- expected = DataFrame({"Per": [pd.Period("2020-01")] * 3})
- tm.assert_frame_equal(expected, result)
+ obj = DataFrame({"Per": [pd.Period("2020-01")] * 3})
+ if frame_or_series is not DataFrame:
+ obj = obj["Per"]
+
+ expected = obj.copy()
+ result = obj.replace(1.0, 0.0)
+ tm.assert_equal(expected, result)
def test_replace_value_category_type(self):
"""
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index 27cf15b4e187b..565debb98d8cc 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -424,10 +424,12 @@ def test_replace_only_one_dictlike_arg(self):
with pytest.raises(ValueError, match=msg):
ser.replace(to_replace, value)
- def test_replace_extension_other(self):
+ def test_replace_extension_other(self, frame_or_series):
# https://github.com/pandas-dev/pandas/issues/34530
- ser = pd.Series(pd.array([1, 2, 3], dtype="Int64"))
- ser.replace("", "") # no exception
+ obj = frame_or_series(pd.array([1, 2, 3], dtype="Int64"))
+ result = obj.replace("", "") # no exception
+ # should not have changed dtype
+ tm.assert_equal(obj, result)
def test_replace_with_compiled_regex(self):
# https://github.com/pandas-dev/pandas/issues/35680
| - [ ] 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/37781 | 2020-11-12T03:49:20Z | 2020-11-13T13:23:38Z | 2020-11-13T13:23:38Z | 2020-11-13T16:19:35Z |
BUG: adding Timedelta to DatetimeIndex raising incorrectly | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index a29ae1912e338..3b1f64e730830 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -14,7 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
--
+- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index f2f843886e802..c4e5da3c85ce8 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -964,7 +964,7 @@ def _add_timedeltalike_scalar(self, other):
# adding a scalar preserves freq
new_freq = self.freq
- return type(self)(new_values, dtype=self.dtype, freq=new_freq)
+ return type(self)._simple_new(new_values, dtype=self.dtype, freq=new_freq)
def _add_timedelta_arraylike(self, other):
"""
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index 375a88f2f2634..88c837e32d261 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -7,7 +7,7 @@
import pytest
import pandas as pd
-from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets
+from pandas import DatetimeIndex, Index, Timedelta, Timestamp, date_range, offsets
import pandas._testing as tm
@@ -408,3 +408,15 @@ def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
dtype="UInt32",
)
tm.assert_frame_equal(result, expected_data_frame)
+
+
+def test_add_timedelta_preserves_freq():
+ # GH#37295 should hold for any DTI with freq=None or Tick freq
+ tz = "Canada/Eastern"
+ dti = date_range(
+ start=Timestamp("2019-03-26 00:00:00-0400", tz=tz),
+ end=Timestamp("2020-10-17 00:00:00-0400", tz=tz),
+ freq="D",
+ )
+ result = dti + Timedelta(days=1)
+ assert result.freq == dti.freq
| - [x] closes #37295
- [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/37780 | 2020-11-12T03:39:27Z | 2020-11-13T04:40:04Z | 2020-11-13T04:40:04Z | 2020-11-13T04:56:53Z |
BUG: Groupby head/tail with axis=1 fails | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index f751a91cecf19..0d3912847dca0 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -543,6 +543,8 @@ Groupby/resample/rolling
- Bug in :meth:`df.groupby(..).quantile() <pandas.core.groupby.DataFrameGroupBy.quantile>` and :meth:`df.resample(..).quantile() <pandas.core.resample.Resampler.quantile>` raised ``TypeError`` when values were of type ``Timedelta`` (:issue:`29485`)
- Bug in :meth:`Rolling.median` and :meth:`Rolling.quantile` returned wrong values for :class:`BaseIndexer` subclasses with non-monotonic starting or ending points for windows (:issue:`37153`)
- Bug in :meth:`DataFrame.groupby` dropped ``nan`` groups from result with ``dropna=False`` when grouping over a single column (:issue:`35646`, :issue:`35542`)
+- Bug in :meth:`DataFrameGroupBy.head`, :meth:`DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`)
+
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 32023576b0a91..e3fceb9bf0a06 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2742,7 +2742,10 @@ def head(self, n=5):
"""
self._reset_group_selection()
mask = self._cumcount_array() < n
- return self._selected_obj[mask]
+ if self.axis == 0:
+ return self._selected_obj[mask]
+ else:
+ return self._selected_obj.iloc[:, mask]
@Substitution(name="groupby")
@Substitution(see_also=_common_see_also)
@@ -2776,7 +2779,10 @@ def tail(self, n=5):
"""
self._reset_group_selection()
mask = self._cumcount_array(ascending=False) < n
- return self._selected_obj[mask]
+ if self.axis == 0:
+ return self._selected_obj[mask]
+ else:
+ return self._selected_obj.iloc[:, mask]
def _reindex_output(
self, output: OutputFrameOrSeries, fill_value: Scalar = np.NaN
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 10394ea997775..699cd88b5c53c 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -513,6 +513,30 @@ def test_groupby_head_tail(op, n, expected_rows, columns, as_index):
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize(
+ "op, n, expected_cols",
+ [
+ ("head", -1, []),
+ ("head", 0, []),
+ ("head", 1, [0, 2]),
+ ("head", 7, [0, 1, 2]),
+ ("tail", -1, []),
+ ("tail", 0, []),
+ ("tail", 1, [1, 2]),
+ ("tail", 7, [0, 1, 2]),
+ ],
+)
+def test_groupby_head_tail_axis_1(op, n, expected_cols):
+ # GH 9772
+ df = DataFrame(
+ [[1, 2, 3], [1, 4, 5], [2, 6, 7], [3, 8, 9]], columns=["A", "B", "C"]
+ )
+ g = df.groupby([0, 0, 1], axis=1)
+ expected = df.iloc[:, expected_cols]
+ result = getattr(g, op)(n)
+ tm.assert_frame_equal(result, expected)
+
+
def test_group_selection_cache():
# GH 12839 nth, head, and tail should return same result consistently
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This potentially closes #9772. The other issue there involves the perhaps unexpected fact that using `axis=1` with `groupby(...).apply` does _not_ transpose the groups that the function is going to be applied to. I've expressed my thoughts on why we should not do so in https://github.com/pandas-dev/pandas/issues/9772#issuecomment-723498819. | https://api.github.com/repos/pandas-dev/pandas/pulls/37778 | 2020-11-12T00:53:11Z | 2020-11-13T04:43:10Z | 2020-11-13T04:43:10Z | 2020-12-06T14:04:57Z |
BUG: Bug in xs ignored droplevel | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 22a0fb7a45318..f31c4d38b2bd6 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -475,6 +475,7 @@ Indexing
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when numeric label was given for object :class:`Index` although label was in :class:`Index` (:issue:`26491`)
- Bug in :meth:`DataFrame.loc` returned requested key plus missing values when ``loc`` was applied to single level from :class:`MultiIndex` (:issue:`27104`)
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using a listlike indexer containing NA values (:issue:`37722`)
+- Bug in :meth:`DataFrame.xs` ignored ``droplevel=False`` for columns (:issue:`19056`)
Missing
^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 24c1ae971686e..72978dd842918 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3708,18 +3708,21 @@ class animal locomotion
return result
if axis == 1:
- return self[key]
+ if drop_level:
+ return self[key]
+ index = self.columns
+ else:
+ index = self.index
- index = self.index
if isinstance(index, MultiIndex):
try:
- loc, new_index = self.index._get_loc_level(
+ loc, new_index = index._get_loc_level(
key, level=0, drop_level=drop_level
)
except TypeError as e:
raise TypeError(f"Expected label or tuple of labels, got {key}") from e
else:
- loc = self.index.get_loc(key)
+ loc = index.get_loc(key)
if isinstance(loc, np.ndarray):
if loc.dtype == np.bool_:
@@ -3729,9 +3732,9 @@ class animal locomotion
return self._take_with_is_copy(loc, axis=axis)
if not is_scalar(loc):
- new_index = self.index[loc]
+ new_index = index[loc]
- if is_scalar(loc):
+ if is_scalar(loc) and axis == 0:
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
@@ -3747,7 +3750,10 @@ class animal locomotion
name=self.index[loc],
dtype=new_values.dtype,
)
-
+ elif is_scalar(loc):
+ result = self.iloc[:, [loc]]
+ elif axis == 1:
+ result = self.iloc[:, loc]
else:
result = self.iloc[loc]
result.index = new_index
diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py
index 11e076f313540..a90141e9fad60 100644
--- a/pandas/tests/frame/indexing/test_xs.py
+++ b/pandas/tests/frame/indexing/test_xs.py
@@ -297,3 +297,25 @@ def test_xs_levels_raises(self, klass):
msg = "Index must be a MultiIndex"
with pytest.raises(TypeError, match=msg):
obj.xs(0, level="as")
+
+ def test_xs_multiindex_droplevel_false(self):
+ # GH#19056
+ mi = MultiIndex.from_tuples(
+ [("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
+ )
+ df = DataFrame([[1, 2, 3]], columns=mi)
+ result = df.xs("a", axis=1, drop_level=False)
+ expected = DataFrame(
+ [[1, 2]],
+ columns=MultiIndex.from_tuples(
+ [("a", "x"), ("a", "y")], names=["level1", "level2"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_xs_droplevel_false(self):
+ # GH#19056
+ df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
+ result = df.xs("a", axis=1, drop_level=False)
+ expected = DataFrame({"a": [1]})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_xs.py b/pandas/tests/series/indexing/test_xs.py
index 1a23b09bde816..ca7ed50ab8875 100644
--- a/pandas/tests/series/indexing/test_xs.py
+++ b/pandas/tests/series/indexing/test_xs.py
@@ -50,3 +50,18 @@ def test_series_getitem_multiindex_xs(xs):
result = ser.xs("20130903", level=1)
tm.assert_series_equal(result, expected)
+
+ def test_series_xs_droplevel_false(self):
+ # GH: 19056
+ mi = MultiIndex.from_tuples(
+ [("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
+ )
+ df = Series([1, 1, 1], index=mi)
+ result = df.xs("a", axis=0, drop_level=False)
+ expected = Series(
+ [1, 1],
+ index=MultiIndex.from_tuples(
+ [("a", "x"), ("a", "y")], names=["level1", "level2"]
+ ),
+ )
+ tm.assert_series_equal(result, expected)
| - [x] closes #19056
- [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/37776 | 2020-11-11T23:43:44Z | 2020-11-13T13:09:29Z | 2020-11-13T13:09:29Z | 2020-11-14T13:08:26Z |
CLN: _get_daily_rule | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index f2f843886e802..15b6227a96603 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -143,14 +143,6 @@ def _scalar_from_string(self, value: str) -> DTScalarOrNaT:
"""
raise AbstractMethodError(self)
- @classmethod
- def _rebox_native(cls, value: int) -> Union[int, np.datetime64, np.timedelta64]:
- """
- Box an integer unboxed via _unbox_scalar into the native type for
- the underlying ndarray.
- """
- raise AbstractMethodError(cls)
-
def _unbox_scalar(
self, value: DTScalarOrNaT, setitem: bool = False
) -> Union[np.int64, np.datetime64, np.timedelta64]:
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 8ef6dac2862db..0d5598fcaf890 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -321,13 +321,7 @@ def _infer_daily_rule(self) -> Optional[str]:
return _maybe_add_count(monthly_rule, self.mdiffs[0])
if self.is_unique:
- days = self.deltas[0] / _ONE_DAY
- if days % 7 == 0:
- # Weekly
- day = int_to_weekday[self.rep_stamp.weekday()]
- return _maybe_add_count(f"W-{day}", days / 7)
- else:
- return _maybe_add_count("D", days)
+ return self._get_daily_rule()
if self._is_business_daily():
return "B"
@@ -338,6 +332,16 @@ def _infer_daily_rule(self) -> Optional[str]:
return None
+ def _get_daily_rule(self) -> Optional[str]:
+ days = self.deltas[0] / _ONE_DAY
+ if days % 7 == 0:
+ # Weekly
+ wd = int_to_weekday[self.rep_stamp.weekday()]
+ alias = f"W-{wd}"
+ return _maybe_add_count(alias, days / 7)
+ else:
+ return _maybe_add_count("D", days)
+
def _get_annual_rule(self) -> Optional[str]:
if len(self.ydiffs) > 1:
return None
@@ -406,14 +410,7 @@ def _get_wom_rule(self) -> Optional[str]:
class _TimedeltaFrequencyInferer(_FrequencyInferer):
def _infer_daily_rule(self):
if self.is_unique:
- days = self.deltas[0] / _ONE_DAY
- if days % 7 == 0:
- # Weekly
- wd = int_to_weekday[self.rep_stamp.weekday()]
- alias = f"W-{wd}"
- return _maybe_add_count(alias, days / 7)
- else:
- return _maybe_add_count("D", days)
+ return self._get_daily_rule()
def _is_multiple(us, mult: int) -> bool:
| Broken off from branch addressing the infer_freq bug mentioned on today's dev call. | https://api.github.com/repos/pandas-dev/pandas/pulls/37775 | 2020-11-11T23:40:21Z | 2020-11-13T04:47:37Z | 2020-11-13T04:47:37Z | 2020-11-13T04:49:53Z |
TST/REF: collect Index setop, indexing tests | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 9e248f0613893..3c0e4d83964c5 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -363,6 +363,7 @@ def test_numpy_argsort(self, index):
# cannot be changed at the moment due to
# backwards compatibility concerns
if isinstance(type(index), (CategoricalIndex, RangeIndex)):
+ # TODO: why type(index)?
msg = "the 'axis' parameter is not supported"
with pytest.raises(ValueError, match=msg):
np.argsort(index, axis=1)
@@ -375,49 +376,6 @@ def test_numpy_argsort(self, index):
with pytest.raises(ValueError, match=msg):
np.argsort(index, order=("a", "b"))
- def test_take(self, index):
- indexer = [4, 3, 0, 2]
- if len(index) < 5:
- # not enough elements; ignore
- return
-
- result = index.take(indexer)
- expected = index[indexer]
- assert result.equals(expected)
-
- if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
- # GH 10791
- msg = r"'(.*Index)' object has no attribute 'freq'"
- with pytest.raises(AttributeError, match=msg):
- index.freq
-
- def test_take_invalid_kwargs(self):
- idx = self.create_index()
- indices = [1, 2]
-
- msg = r"take\(\) got an unexpected keyword argument 'foo'"
- with pytest.raises(TypeError, match=msg):
- idx.take(indices, foo=2)
-
- msg = "the 'out' parameter is not supported"
- with pytest.raises(ValueError, match=msg):
- idx.take(indices, out=indices)
-
- msg = "the 'mode' parameter is not supported"
- with pytest.raises(ValueError, match=msg):
- idx.take(indices, mode="clip")
-
- def test_take_minus1_without_fill(self, index):
- # -1 does not get treated as NA unless allow_fill=True is passed
- if len(index) == 0:
- # Test is not applicable
- return
-
- result = index.take([0, 0, -1])
-
- expected = index.take([0, 0, len(index) - 1])
- tm.assert_index_equal(result, expected)
-
def test_repeat(self):
rep = 2
i = self.create_index()
@@ -456,117 +414,6 @@ def test_where(self, klass):
result = i.where(klass(cond))
tm.assert_index_equal(result, expected)
- @pytest.mark.parametrize("case", [0.5, "xxx"])
- @pytest.mark.parametrize(
- "method", ["intersection", "union", "difference", "symmetric_difference"]
- )
- def test_set_ops_error_cases(self, case, method, index):
- # non-iterable input
- msg = "Input must be Index or array-like"
- with pytest.raises(TypeError, match=msg):
- getattr(index, method)(case)
-
- def test_intersection_base(self, index):
- if isinstance(index, CategoricalIndex):
- return
-
- first = index[:5]
- second = index[:3]
- intersect = first.intersection(second)
- assert tm.equalContents(intersect, second)
-
- if is_datetime64tz_dtype(index.dtype):
- # The second.values below will drop tz, so the rest of this test
- # is not applicable.
- return
-
- # GH 10149
- cases = [klass(second.values) for klass in [np.array, Series, list]]
- for case in cases:
- result = first.intersection(case)
- assert tm.equalContents(result, second)
-
- if isinstance(index, MultiIndex):
- msg = "other must be a MultiIndex or a list of tuples"
- with pytest.raises(TypeError, match=msg):
- first.intersection([1, 2, 3])
-
- def test_union_base(self, index):
- first = index[3:]
- second = index[:5]
- everything = index
- union = first.union(second)
- assert tm.equalContents(union, everything)
-
- if is_datetime64tz_dtype(index.dtype):
- # The second.values below will drop tz, so the rest of this test
- # is not applicable.
- return
-
- # GH 10149
- cases = [klass(second.values) for klass in [np.array, Series, list]]
- for case in cases:
- if not isinstance(index, CategoricalIndex):
- result = first.union(case)
- assert tm.equalContents(result, everything), (
- result,
- everything,
- type(case),
- )
-
- if isinstance(index, MultiIndex):
- msg = "other must be a MultiIndex or a list of tuples"
- with pytest.raises(TypeError, match=msg):
- first.union([1, 2, 3])
-
- def test_difference_base(self, sort, index):
- first = index[2:]
- second = index[:4]
- if isinstance(index, CategoricalIndex) or index.is_boolean():
- answer = []
- else:
- answer = index[4:]
- result = first.difference(second, sort)
- assert tm.equalContents(result, answer)
-
- # GH 10149
- cases = [klass(second.values) for klass in [np.array, Series, list]]
- for case in cases:
- if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
- assert type(result) == type(answer)
- tm.assert_numpy_array_equal(
- result.sort_values().asi8, answer.sort_values().asi8
- )
- else:
- result = first.difference(case, sort)
- assert tm.equalContents(result, answer)
-
- if isinstance(index, MultiIndex):
- msg = "other must be a MultiIndex or a list of tuples"
- with pytest.raises(TypeError, match=msg):
- first.difference([1, 2, 3], sort)
-
- def test_symmetric_difference(self, index):
- if isinstance(index, CategoricalIndex):
- return
-
- first = index[1:]
- second = index[:-1]
- answer = index[[0, -1]]
- result = first.symmetric_difference(second)
- assert tm.equalContents(result, answer)
-
- # GH 10149
- cases = [klass(second.values) for klass in [np.array, Series, list]]
- for case in cases:
- result = first.symmetric_difference(case)
- assert tm.equalContents(result, answer)
-
- if isinstance(index, MultiIndex):
- msg = "other must be a MultiIndex or a list of tuples"
- with pytest.raises(TypeError, match=msg):
- first.symmetric_difference([1, 2, 3])
-
def test_insert_base(self, index):
result = index[1:4]
@@ -601,7 +448,8 @@ def test_delete_base(self, index):
def test_equals(self, index):
if isinstance(index, IntervalIndex):
- # IntervalIndex tested separately
+ # IntervalIndex tested separately, the index.equals(index.astype(object))
+ # fails for IntervalIndex
return
assert index.equals(index)
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index 508bd2f566507..f329a04612e33 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import Float64Index, Int64Index, Series, UInt64Index
+from pandas import Float64Index, Index, Int64Index, Series, UInt64Index
import pandas._testing as tm
@@ -241,3 +241,20 @@ def test_contains_float64_nans(self):
def test_contains_float64_not_nans(self):
index = Float64Index([1.0, 2.0, np.nan])
assert 1.0 in index
+
+
+class TestGetSliceBounds:
+ @pytest.mark.parametrize("kind", ["getitem", "loc", None])
+ @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
+ def test_get_slice_bounds_within(self, kind, side, expected):
+ index = Index(range(6))
+ result = index.get_slice_bound(4, kind=kind, side=side)
+ assert result == expected
+
+ @pytest.mark.parametrize("kind", ["getitem", "loc", None])
+ @pytest.mark.parametrize("side", ["left", "right"])
+ @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])
+ def test_get_slice_bounds_outside(self, kind, side, expected, bound):
+ index = Index(range(6))
+ result = index.get_slice_bound(bound, kind=kind, side=side)
+ assert result == expected
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 3750df4b65066..788b6f99806d6 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1082,27 +1082,6 @@ def test_symmetric_difference_non_index(self, sort):
assert tm.equalContents(result, expected)
assert result.name == "new_name"
- def test_difference_type(self, index, sort):
- # GH 20040
- # If taking difference of a set and itself, it
- # needs to preserve the type of the index
- if not index.is_unique:
- return
- result = index.difference(index, sort=sort)
- expected = index.drop(index)
- tm.assert_index_equal(result, expected)
-
- def test_intersection_difference(self, index, sort):
- # GH 20040
- # Test that the intersection of an index with an
- # empty index produces the same index as the difference
- # of an index with itself. Test for all types
- if not index.is_unique:
- return
- inter = index.intersection(index.drop(index))
- diff = index.difference(index, sort=sort)
- tm.assert_index_equal(inter, diff)
-
def test_is_mixed_deprecated(self):
# GH#32922
index = self.create_index()
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index d47582566fe94..d15b560419f6d 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -71,139 +71,6 @@ def test_getitem_error(self, index, itm):
with pytest.raises(IndexError):
index[itm]
- @pytest.mark.parametrize(
- "fname, sname, expected_name",
- [
- ("A", "A", "A"),
- ("A", "B", None),
- ("A", None, None),
- (None, "B", None),
- (None, None, None),
- ],
- )
- def test_corner_union(self, index, fname, sname, expected_name):
- # GH 9943 9862
- # Test unions with various name combinations
- # Do not test MultiIndex or repeats
-
- if isinstance(index, MultiIndex) or not index.is_unique:
- pytest.skip("Not for MultiIndex or repeated indices")
-
- # Test copy.union(copy)
- first = index.copy().set_names(fname)
- second = index.copy().set_names(sname)
- union = first.union(second)
- expected = index.copy().set_names(expected_name)
- tm.assert_index_equal(union, expected)
-
- # Test copy.union(empty)
- first = index.copy().set_names(fname)
- second = index.drop(index).set_names(sname)
- union = first.union(second)
- expected = index.copy().set_names(expected_name)
- tm.assert_index_equal(union, expected)
-
- # Test empty.union(copy)
- first = index.drop(index).set_names(fname)
- second = index.copy().set_names(sname)
- union = first.union(second)
- expected = index.copy().set_names(expected_name)
- tm.assert_index_equal(union, expected)
-
- # Test empty.union(empty)
- first = index.drop(index).set_names(fname)
- second = index.drop(index).set_names(sname)
- union = first.union(second)
- expected = index.drop(index).set_names(expected_name)
- tm.assert_index_equal(union, expected)
-
- @pytest.mark.parametrize(
- "fname, sname, expected_name",
- [
- ("A", "A", "A"),
- ("A", "B", None),
- ("A", None, None),
- (None, "B", None),
- (None, None, None),
- ],
- )
- def test_union_unequal(self, index, fname, sname, expected_name):
- if isinstance(index, MultiIndex) or not index.is_unique:
- pytest.skip("Not for MultiIndex or repeated indices")
-
- # test copy.union(subset) - need sort for unicode and string
- first = index.copy().set_names(fname)
- second = index[1:].set_names(sname)
- union = first.union(second).sort_values()
- expected = index.set_names(expected_name).sort_values()
- tm.assert_index_equal(union, expected)
-
- @pytest.mark.parametrize(
- "fname, sname, expected_name",
- [
- ("A", "A", "A"),
- ("A", "B", None),
- ("A", None, None),
- (None, "B", None),
- (None, None, None),
- ],
- )
- def test_corner_intersect(self, index, fname, sname, expected_name):
- # GH35847
- # Test intersections with various name combinations
-
- if isinstance(index, MultiIndex) or not index.is_unique:
- pytest.skip("Not for MultiIndex or repeated indices")
-
- # Test copy.intersection(copy)
- first = index.copy().set_names(fname)
- second = index.copy().set_names(sname)
- intersect = first.intersection(second)
- expected = index.copy().set_names(expected_name)
- tm.assert_index_equal(intersect, expected)
-
- # Test copy.intersection(empty)
- first = index.copy().set_names(fname)
- second = index.drop(index).set_names(sname)
- intersect = first.intersection(second)
- expected = index.drop(index).set_names(expected_name)
- tm.assert_index_equal(intersect, expected)
-
- # Test empty.intersection(copy)
- first = index.drop(index).set_names(fname)
- second = index.copy().set_names(sname)
- intersect = first.intersection(second)
- expected = index.drop(index).set_names(expected_name)
- tm.assert_index_equal(intersect, expected)
-
- # Test empty.intersection(empty)
- first = index.drop(index).set_names(fname)
- second = index.drop(index).set_names(sname)
- intersect = first.intersection(second)
- expected = index.drop(index).set_names(expected_name)
- tm.assert_index_equal(intersect, expected)
-
- @pytest.mark.parametrize(
- "fname, sname, expected_name",
- [
- ("A", "A", "A"),
- ("A", "B", None),
- ("A", None, None),
- (None, "B", None),
- (None, None, None),
- ],
- )
- def test_intersect_unequal(self, index, fname, sname, expected_name):
- if isinstance(index, MultiIndex) or not index.is_unique:
- pytest.skip("Not for MultiIndex or repeated indices")
-
- # test copy.intersection(subset) - need sort for unicode and string
- first = index.copy().set_names(fname)
- second = index[1:].set_names(sname)
- intersect = first.intersection(second).sort_values()
- expected = index[1:].set_names(expected_name).sort_values()
- tm.assert_index_equal(intersect, expected)
-
def test_to_flat_index(self, index):
# 22866
if isinstance(index, MultiIndex):
@@ -329,13 +196,6 @@ def test_get_unique_index(self, index):
result = i._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, expected)
- def test_mutability(self, index):
- if not len(index):
- pytest.skip("Skip check for empty Index")
- msg = "Index does not support mutable operations"
- with pytest.raises(TypeError, match=msg):
- index[0] = index[0]
-
def test_view(self, index):
assert index.view().name == index.name
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 8910a3731cf8a..538575781b4b2 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -16,10 +16,62 @@
import numpy as np
import pytest
-from pandas import Float64Index, Index, Int64Index, UInt64Index
+from pandas import (
+ DatetimeIndex,
+ Float64Index,
+ Index,
+ Int64Index,
+ PeriodIndex,
+ TimedeltaIndex,
+ UInt64Index,
+)
import pandas._testing as tm
+class TestTake:
+ def test_take_invalid_kwargs(self, index):
+ indices = [1, 2]
+
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
+ with pytest.raises(TypeError, match=msg):
+ index.take(indices, foo=2)
+
+ msg = "the 'out' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ index.take(indices, out=indices)
+
+ msg = "the 'mode' parameter is not supported"
+ with pytest.raises(ValueError, match=msg):
+ index.take(indices, mode="clip")
+
+ def test_take(self, index):
+ indexer = [4, 3, 0, 2]
+ if len(index) < 5:
+ # not enough elements; ignore
+ return
+
+ result = index.take(indexer)
+ expected = index[indexer]
+ assert result.equals(expected)
+
+ if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
+ # GH 10791
+ msg = r"'(.*Index)' object has no attribute 'freq'"
+ with pytest.raises(AttributeError, match=msg):
+ index.freq
+
+ def test_take_minus1_without_fill(self, index):
+ # -1 does not get treated as NA unless allow_fill=True is passed
+ if len(index) == 0:
+ # Test is not applicable
+ return
+
+ result = index.take([0, 0, -1])
+
+ expected = index.take([0, 0, len(index) - 1])
+ tm.assert_index_equal(result, expected)
+
+
class TestContains:
@pytest.mark.parametrize(
"index,val",
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index 0c990b0456b5c..e64cadf7a8069 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -687,20 +687,3 @@ def test_float64_index_difference():
result = string_index.difference(float_index)
tm.assert_index_equal(result, string_index)
-
-
-class TestGetSliceBounds:
- @pytest.mark.parametrize("kind", ["getitem", "loc", None])
- @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
- def test_get_slice_bounds_within(self, kind, side, expected):
- index = Index(range(6))
- result = index.get_slice_bound(4, kind=kind, side=side)
- assert result == expected
-
- @pytest.mark.parametrize("kind", ["getitem", "loc", None])
- @pytest.mark.parametrize("side", ["left", "right"])
- @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])
- def test_get_slice_bounds_outside(self, kind, side, expected, bound):
- index = Index(range(6))
- result = index.get_slice_bound(bound, kind=kind, side=side)
- assert result == expected
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index 7b886a9353322..1be17a9d6116a 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -8,9 +8,19 @@
from pandas.core.dtypes.common import is_dtype_equal
import pandas as pd
-from pandas import Float64Index, Int64Index, RangeIndex, UInt64Index
+from pandas import (
+ CategoricalIndex,
+ DatetimeIndex,
+ Float64Index,
+ Int64Index,
+ MultiIndex,
+ RangeIndex,
+ Series,
+ TimedeltaIndex,
+ UInt64Index,
+)
import pandas._testing as tm
-from pandas.api.types import pandas_dtype
+from pandas.api.types import is_datetime64tz_dtype, pandas_dtype
COMPATIBLE_INCONSISTENT_PAIRS = {
(Int64Index, RangeIndex): (tm.makeIntIndex, tm.makeRangeIndex),
@@ -108,3 +118,283 @@ def test_dunder_inplace_setops_deprecated(index):
with tm.assert_produces_warning(FutureWarning):
index ^= index
+
+
+class TestSetOps:
+ # Set operation tests shared by all indexes in the `index` fixture
+ @pytest.mark.parametrize("case", [0.5, "xxx"])
+ @pytest.mark.parametrize(
+ "method", ["intersection", "union", "difference", "symmetric_difference"]
+ )
+ def test_set_ops_error_cases(self, case, method, index):
+ # non-iterable input
+ msg = "Input must be Index or array-like"
+ with pytest.raises(TypeError, match=msg):
+ getattr(index, method)(case)
+
+ def test_intersection_base(self, index):
+ if isinstance(index, CategoricalIndex):
+ return
+
+ first = index[:5]
+ second = index[:3]
+ intersect = first.intersection(second)
+ assert tm.equalContents(intersect, second)
+
+ if is_datetime64tz_dtype(index.dtype):
+ # The second.values below will drop tz, so the rest of this test
+ # is not applicable.
+ return
+
+ # GH#10149
+ cases = [klass(second.values) for klass in [np.array, Series, list]]
+ for case in cases:
+ result = first.intersection(case)
+ assert tm.equalContents(result, second)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.intersection([1, 2, 3])
+
+ def test_union_base(self, index):
+ first = index[3:]
+ second = index[:5]
+ everything = index
+ union = first.union(second)
+ assert tm.equalContents(union, everything)
+
+ if is_datetime64tz_dtype(index.dtype):
+ # The second.values below will drop tz, so the rest of this test
+ # is not applicable.
+ return
+
+ # GH#10149
+ cases = [klass(second.values) for klass in [np.array, Series, list]]
+ for case in cases:
+ if not isinstance(index, CategoricalIndex):
+ result = first.union(case)
+ assert tm.equalContents(result, everything), (
+ result,
+ everything,
+ type(case),
+ )
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.union([1, 2, 3])
+
+ def test_difference_base(self, sort, index):
+ first = index[2:]
+ second = index[:4]
+ if isinstance(index, CategoricalIndex) or index.is_boolean():
+ answer = []
+ else:
+ answer = index[4:]
+ result = first.difference(second, sort)
+ assert tm.equalContents(result, answer)
+
+ # GH#10149
+ cases = [klass(second.values) for klass in [np.array, Series, list]]
+ for case in cases:
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
+ assert type(result) == type(answer)
+ tm.assert_numpy_array_equal(
+ result.sort_values().asi8, answer.sort_values().asi8
+ )
+ else:
+ result = first.difference(case, sort)
+ assert tm.equalContents(result, answer)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.difference([1, 2, 3], sort)
+
+ def test_symmetric_difference(self, index):
+ if isinstance(index, CategoricalIndex):
+ return
+ if len(index) < 2:
+ return
+ if index[0] in index[1:] or index[-1] in index[:-1]:
+ # index fixture has e.g. an index of bools that does not satisfy this,
+ # another with [0, 0, 1, 1, 2, 2]
+ return
+
+ first = index[1:]
+ second = index[:-1]
+ answer = index[[0, -1]]
+ result = first.symmetric_difference(second)
+ assert tm.equalContents(result, answer)
+
+ # GH#10149
+ cases = [klass(second.values) for klass in [np.array, Series, list]]
+ for case in cases:
+ if is_datetime64tz_dtype(first):
+ with pytest.raises(ValueError, match="Tz-aware"):
+ # `second.values` casts to tznaive
+ # TODO: should the symmetric_difference then be the union?
+ first.symmetric_difference(case)
+ continue
+ result = first.symmetric_difference(case)
+ assert tm.equalContents(result, answer)
+
+ if isinstance(index, MultiIndex):
+ msg = "other must be a MultiIndex or a list of tuples"
+ with pytest.raises(TypeError, match=msg):
+ first.symmetric_difference([1, 2, 3])
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_corner_union(self, index, fname, sname, expected_name):
+ # GH#9943, GH#9862
+ # Test unions with various name combinations
+ # Do not test MultiIndex or repeats
+
+ if isinstance(index, MultiIndex) or not index.is_unique:
+ pytest.skip("Not for MultiIndex or repeated indices")
+
+ # Test copy.union(copy)
+ first = index.copy().set_names(fname)
+ second = index.copy().set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test copy.union(empty)
+ first = index.copy().set_names(fname)
+ second = index.drop(index).set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test empty.union(copy)
+ first = index.drop(index).set_names(fname)
+ second = index.copy().set_names(sname)
+ union = first.union(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ # Test empty.union(empty)
+ first = index.drop(index).set_names(fname)
+ second = index.drop(index).set_names(sname)
+ union = first.union(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(union, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_union_unequal(self, index, fname, sname, expected_name):
+ if isinstance(index, MultiIndex) or not index.is_unique:
+ pytest.skip("Not for MultiIndex or repeated indices")
+
+ # test copy.union(subset) - need sort for unicode and string
+ first = index.copy().set_names(fname)
+ second = index[1:].set_names(sname)
+ union = first.union(second).sort_values()
+ expected = index.set_names(expected_name).sort_values()
+ tm.assert_index_equal(union, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_corner_intersect(self, index, fname, sname, expected_name):
+ # GH#35847
+ # Test intersections with various name combinations
+
+ if isinstance(index, MultiIndex) or not index.is_unique:
+ pytest.skip("Not for MultiIndex or repeated indices")
+
+ # Test copy.intersection(copy)
+ first = index.copy().set_names(fname)
+ second = index.copy().set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.copy().set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test copy.intersection(empty)
+ first = index.copy().set_names(fname)
+ second = index.drop(index).set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test empty.intersection(copy)
+ first = index.drop(index).set_names(fname)
+ second = index.copy().set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ # Test empty.intersection(empty)
+ first = index.drop(index).set_names(fname)
+ second = index.drop(index).set_names(sname)
+ intersect = first.intersection(second)
+ expected = index.drop(index).set_names(expected_name)
+ tm.assert_index_equal(intersect, expected)
+
+ @pytest.mark.parametrize(
+ "fname, sname, expected_name",
+ [
+ ("A", "A", "A"),
+ ("A", "B", None),
+ ("A", None, None),
+ (None, "B", None),
+ (None, None, None),
+ ],
+ )
+ def test_intersect_unequal(self, index, fname, sname, expected_name):
+ if isinstance(index, MultiIndex) or not index.is_unique:
+ pytest.skip("Not for MultiIndex or repeated indices")
+
+ # test copy.intersection(subset) - need sort for unicode and string
+ first = index.copy().set_names(fname)
+ second = index[1:].set_names(sname)
+ intersect = first.intersection(second).sort_values()
+ expected = index[1:].set_names(expected_name).sort_values()
+ tm.assert_index_equal(intersect, expected)
+
+ def test_difference_preserves_type_empty(self, index, sort):
+ # GH#20040
+ # If taking difference of a set and itself, it
+ # needs to preserve the type of the index
+ if not index.is_unique:
+ return
+ result = index.difference(index, sort=sort)
+ expected = index.drop(index)
+ tm.assert_index_equal(result, expected)
+
+ def test_intersection_difference_match_empty(self, index, sort):
+ # GH#20040
+ # Test that the intersection of an index with an
+ # empty index produces the same index as the difference
+ # of an index with itself. Test for all types
+ if not index.is_unique:
+ return
+ inter = index.intersection(index.drop(index))
+ diff = index.difference(index, sort=sort)
+ tm.assert_index_equal(inter, diff)
| https://api.github.com/repos/pandas-dev/pandas/pulls/37773 | 2020-11-11T23:00:11Z | 2020-11-13T04:49:18Z | 2020-11-13T04:49:18Z | 2020-11-13T04:53:50Z | |
Fix pivot index bug | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index f751a91cecf19..fba430ac1b5b6 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -553,6 +553,7 @@ Reshaping
- Bug in :meth:`DataFrame.agg` with ``func={'name':<FUNC>}`` incorrectly raising ``TypeError`` when ``DataFrame.columns==['Name']`` (:issue:`36212`)
- Bug in :meth:`Series.transform` would give incorrect results or raise when the argument ``func`` was dictionary (:issue:`35811`)
- Bug in :meth:`DataFrame.pivot` did not preserve :class:`MultiIndex` level names for columns when rows and columns both multiindexed (:issue:`36360`)
+- Bug in :meth:`DataFrame.pivot` modified ``index`` argument when ``columns`` was passed but ``values`` was not (:issue:`37635`)
- Bug in :func:`join` returned a non deterministic level-order for the resulting :class:`MultiIndex` (:issue:`36910`)
- Bug in :meth:`DataFrame.combine_first()` caused wrong alignment with dtype ``string`` and one level of ``MultiIndex`` containing only ``NA`` (:issue:`37591`)
- Fixed regression in :func:`merge` on merging DatetimeIndex with empty DataFrame (:issue:`36895`)
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 8fae01cb30d3d..c1198cdfcda81 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -450,10 +450,9 @@ def pivot(
cols = com.convert_to_list_like(index)
else:
cols = []
- cols.extend(columns)
append = index is None
- indexed = data.set_index(cols, append=append)
+ indexed = data.set_index(cols + columns, append=append)
else:
if index is None:
index = [Series(data.index, name=data.index.name)]
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index adab64577ee7a..e08876226cbc8 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -2153,3 +2153,41 @@ def test_pivot_index_none(self):
expected.columns.name = "columns"
tm.assert_frame_equal(result, expected)
+
+ def test_pivot_index_list_values_none_immutable_args(self):
+ # GH37635
+ df = DataFrame(
+ {
+ "lev1": [1, 1, 1, 2, 2, 2],
+ "lev2": [1, 1, 2, 1, 1, 2],
+ "lev3": [1, 2, 1, 2, 1, 2],
+ "lev4": [1, 2, 3, 4, 5, 6],
+ "values": [0, 1, 2, 3, 4, 5],
+ }
+ )
+ index = ["lev1", "lev2"]
+ columns = ["lev3"]
+ result = df.pivot(index=index, columns=columns, values=None)
+
+ expected = DataFrame(
+ np.array(
+ [
+ [1.0, 2.0, 0.0, 1.0],
+ [3.0, np.nan, 2.0, np.nan],
+ [5.0, 4.0, 4.0, 3.0],
+ [np.nan, 6.0, np.nan, 5.0],
+ ]
+ ),
+ index=MultiIndex.from_arrays(
+ [(1, 1, 2, 2), (1, 2, 1, 2)], names=["lev1", "lev2"]
+ ),
+ columns=MultiIndex.from_arrays(
+ [("lev4", "lev4", "values", "values"), (1, 2, 1, 2)],
+ names=[None, "lev3"],
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ assert index == ["lev1", "lev2"]
+ assert columns == ["lev3"]
| Previously, the variable "cols" was created solely to concatenate
the lists "index" and "columns" when the "values" parameter was
left as None. It did so in a way that it modified the variable
passed as "index" using list.extend(), affecting the caller's
namespace.
This change simply uses an anonymous list in place of the
variable "cols"
Had some trouble setting up the dev environment to build pandas from source,
so no tests checked or docs built. However, it's fairly minor change, so hoping
that it builds green regardless...
- [X] closes #37635
- [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/37771 | 2020-11-11T22:05:50Z | 2020-11-14T02:21:09Z | 2020-11-14T02:21:09Z | 2020-11-14T18:46:23Z |
TST: Isin converted floats unnecessarily to int causing rounding issues | diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py
index 071b1f3f75f44..76a84aac786c8 100644
--- a/pandas/tests/series/methods/test_isin.py
+++ b/pandas/tests/series/methods/test_isin.py
@@ -145,6 +145,14 @@ def test_isin_period_freq_mismatch(self):
res = pd.core.algorithms.isin(ser, other)
tm.assert_numpy_array_equal(res, expected)
+ @pytest.mark.parametrize("values", [[-9.0, 0.0], [-9, 0]])
+ def test_isin_float_in_int_series(self, values):
+ # GH#19356 GH#21804
+ ser = Series(values)
+ result = ser.isin([-9, -0.5])
+ expected = Series([True, False])
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.slow
def test_isin_large_series_mixed_dtypes_and_nan():
| - [x] closes #19356
- [x] closes #21804
- [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/37770 | 2020-11-11T22:03:28Z | 2020-12-29T23:44:28Z | 2020-12-29T23:44:27Z | 2020-12-30T09:10:11Z |
CI: remove unused import | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 49a7229c420c8..24c1ae971686e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -54,7 +54,7 @@
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError, InvalidIndexError
-from pandas.util._decorators import Appender, doc, rewrite_axis_style_signature
+from pandas.util._decorators import doc, rewrite_axis_style_signature
from pandas.util._validators import (
validate_bool_kwarg,
validate_fillna_kwargs,
| xref #37703 | https://api.github.com/repos/pandas-dev/pandas/pulls/37767 | 2020-11-11T20:53:26Z | 2020-11-11T22:20:43Z | 2020-11-11T22:20:43Z | 2020-11-11T22:20:51Z |
Bug in loc did not raise KeyError when missing combination with slice(None) was given | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index ecea79be5b4dc..cce6b1b01d802 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -611,6 +611,7 @@ Indexing
- Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty :class:`DataFrame` with ``tolerance`` not None or ``method="nearest"`` (:issue:`27315`)
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
+- Bug in :meth:`DataFrame.loc` did not raise ``KeyError`` when missing combination was given with ``slice(None)`` for remaining levels (:issue:`19556`)
Missing
^^^^^^^
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 9eb34d920a328..76c5ee539e510 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3132,19 +3132,26 @@ def _convert_to_indexer(r) -> Int64Index:
r = r.nonzero()[0]
return Int64Index(r)
- def _update_indexer(idxr: Optional[Index], indexer: Optional[Index]) -> Index:
+ def _update_indexer(
+ idxr: Optional[Index], indexer: Optional[Index], key
+ ) -> Index:
if indexer is None:
indexer = Index(np.arange(n))
if idxr is None:
return indexer
- return indexer.intersection(idxr)
+ indexer_intersection = indexer.intersection(idxr)
+ if indexer_intersection.empty and not idxr.empty and not indexer.empty:
+ raise KeyError(key)
+ return indexer_intersection
for i, k in enumerate(seq):
if com.is_bool_indexer(k):
# a boolean indexer, must be the same length!
k = np.asarray(k)
- indexer = _update_indexer(_convert_to_indexer(k), indexer=indexer)
+ indexer = _update_indexer(
+ _convert_to_indexer(k), indexer=indexer, key=seq
+ )
elif is_list_like(k):
# a collection of labels to include from this level (these
@@ -3164,14 +3171,14 @@ def _update_indexer(idxr: Optional[Index], indexer: Optional[Index]) -> Index:
continue
if indexers is not None:
- indexer = _update_indexer(indexers, indexer=indexer)
+ indexer = _update_indexer(indexers, indexer=indexer, key=seq)
else:
# no matches we are done
return np.array([], dtype=np.int64)
elif com.is_null_slice(k):
# empty slice
- indexer = _update_indexer(None, indexer=indexer)
+ indexer = _update_indexer(None, indexer=indexer, key=seq)
elif isinstance(k, slice):
@@ -3181,6 +3188,7 @@ def _update_indexer(idxr: Optional[Index], indexer: Optional[Index]) -> Index:
self._get_level_indexer(k, level=i, indexer=indexer)
),
indexer=indexer,
+ key=seq,
)
else:
# a single label
@@ -3189,6 +3197,7 @@ def _update_indexer(idxr: Optional[Index], indexer: Optional[Index]) -> Index:
self.get_loc_level(k, level=i, drop_level=False)[0]
),
indexer=indexer,
+ key=seq,
)
# empty indexer
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 165d34180dfab..22ffca46a4829 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -608,6 +608,25 @@ def test_missing_key_raises_keyerror2(self):
with pytest.raises(KeyError, match=r"\(0, 3\)"):
ser.loc[0, 3]
+ def test_missing_key_combination(self):
+ # GH: 19556
+ mi = MultiIndex.from_arrays(
+ [
+ np.array(["a", "a", "b", "b"]),
+ np.array(["1", "2", "2", "3"]),
+ np.array(["c", "d", "c", "d"]),
+ ],
+ names=["one", "two", "three"],
+ )
+ df = DataFrame(np.random.rand(4, 3), index=mi)
+ msg = r"\('b', '1', slice\(None, None, None\)\)"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[("b", "1", slice(None)), :]
+ with pytest.raises(KeyError, match=msg):
+ df.index.get_locs(("b", "1", slice(None)))
+ with pytest.raises(KeyError, match=r"\('b', '1'\)"):
+ df.loc[("b", "1"), :]
+
def test_getitem_loc_commutability(multiindex_year_month_day_dataframe_random_data):
df = multiindex_year_month_day_dataframe_random_data
| - [x] closes #19556
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Additional question: When an non existent key is given for ``get_locs`` it raises a ``KeyError``. When just a missing combination of keys is given (``(b,1)`` in the new test), while the individual keys exist, an empty array is returned. Is this the expected behavior? | https://api.github.com/repos/pandas-dev/pandas/pulls/37764 | 2020-11-11T20:17:04Z | 2020-11-21T22:21:04Z | 2020-11-21T22:21:04Z | 2020-11-21T23:42:22Z |
BUG: clean the figure windows created by tests | diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py
index b2eeb649276d5..c524b21f1be9e 100644
--- a/pandas/tests/plotting/test_converter.py
+++ b/pandas/tests/plotting/test_converter.py
@@ -70,15 +70,17 @@ def test_registering_no_warning(self):
# Set to the "warn" state, in case this isn't the first test run
register_matplotlib_converters()
ax.plot(s.index, s.values)
+ plt.close()
def test_pandas_plots_register(self):
- pytest.importorskip("matplotlib.pyplot")
+ plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
# Set to the "warn" state, in case this isn't the first test run
with tm.assert_produces_warning(None) as w:
s.plot()
assert len(w) == 0
+ plt.close()
def test_matplotlib_formatters(self):
units = pytest.importorskip("matplotlib.units")
@@ -108,6 +110,7 @@ def test_option_no_warning(self):
register_matplotlib_converters()
with ctx:
ax.plot(s.index, s.values)
+ plt.close()
def test_registry_resets(self):
units = pytest.importorskip("matplotlib.units")
| - [x] closes #35080
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
fixed: FAILED pandas/tests/plotting/test_datetimelike.py::TestTSPlot::test_ts_plot_with_tz['UTC']
reference:
- https://github.com/pandas-dev/pandas/issues/35080#issuecomment-652988132 @StefRe as co-author (have already marked as the co-author in my forked repo, however, I'm not sure whether as well as right here)
- https://stackoverflow.com/a/8228808/7069618
- https://stackoverflow.com/a/33343289/7069618 | https://api.github.com/repos/pandas-dev/pandas/pulls/37762 | 2020-11-11T18:30:43Z | 2020-11-12T16:23:38Z | 2020-11-12T16:23:38Z | 2020-11-12T16:23:53Z |
BUG: Bug in loc raised ValueError when setting value via boolean list | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 2f2e8aed6fdb8..7c51eeff4dc95 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -844,6 +844,7 @@ Indexing
- Bug in :meth:`Index.union` dropping duplicate ``Index`` values when ``Index`` was not monotonic or ``sort`` was set to ``False`` (:issue:`36289`, :issue:`31326`, :issue:`40862`)
- Bug in :meth:`CategoricalIndex.get_indexer` failing to raise ``InvalidIndexError`` when non-unique (:issue:`38372`)
+- Bug in :meth:`Series.loc` raising ``ValueError`` when input was filtered with a boolean list and values to set were a list with lower dimension (:issue:`20438`)
- Bug in inserting many new columns into a :class:`DataFrame` causing incorrect subsequent indexing behavior (:issue:`38380`)
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` when setting multiple values to duplicate columns (:issue:`15695`)
- Bug in :meth:`DataFrame.loc`, :meth:`Series.loc`, :meth:`DataFrame.__getitem__` and :meth:`Series.__getitem__` returning incorrect elements for non-monotonic :class:`DatetimeIndex` for string slices (:issue:`33146`)
diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index 4f3f536cd3290..ed4b1a3fbb39c 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -166,6 +166,8 @@ def check_setitem_lengths(indexer, value, values) -> bool:
if is_list_like(value):
if len(indexer) != len(value) and values.ndim == 1:
# boolean with truth values == len of the value is ok too
+ if isinstance(indexer, list):
+ indexer = np.array(indexer)
if not (
isinstance(indexer, np.ndarray)
and indexer.dtype == np.bool_
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index 1f50dacc4dffd..281bfb19eb6fa 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -1114,6 +1114,20 @@ def test_iloc_interval(self):
expected = DataFrame({Interval(1, 2): [2, 3]})
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("indexing_func", [list, np.array])
+ @pytest.mark.parametrize("rhs_func", [list, np.array])
+ def test_loc_setitem_boolean_list(self, rhs_func, indexing_func):
+ # GH#20438 testing specifically list key, not arraylike
+ ser = Series([0, 1, 2])
+ ser.iloc[indexing_func([True, False, True])] = rhs_func([5, 10])
+ expected = Series([5, 1, 10])
+ tm.assert_series_equal(ser, expected)
+
+ df = DataFrame({"a": [0, 1, 2]})
+ df.iloc[indexing_func([True, False, True])] = rhs_func([[5], [10]])
+ expected = DataFrame({"a": [5, 1, 10]})
+ tm.assert_frame_equal(df, expected)
+
class TestILocErrors:
# NB: this test should work for _any_ Series we can pass as
| - [x] closes #20438
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Not quite sure if conversion to numpy array is necessary, but ``is_dtype_bool`` does not accept lists
| https://api.github.com/repos/pandas-dev/pandas/pulls/37761 | 2020-11-11T16:22:50Z | 2021-05-25T09:29:09Z | 2021-05-25T09:29:09Z | 2021-05-25T09:34:03Z |
DOC: test organization | diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst
index f8a6bb6deb52d..e842c827b417f 100644
--- a/doc/source/development/index.rst
+++ b/doc/source/development/index.rst
@@ -16,6 +16,7 @@ Development
code_style
maintaining
internals
+ test_writing
extending
developer
policies
diff --git a/doc/source/development/test_writing.rst b/doc/source/development/test_writing.rst
new file mode 100644
index 0000000000000..d9e24bb76eed8
--- /dev/null
+++ b/doc/source/development/test_writing.rst
@@ -0,0 +1,174 @@
+.. _test_organization:
+
+Test organization
+=================
+Ideally, there should be one, and only one, obvious place for a test to reside.
+Until we reach that ideal, these are some rules of thumb for where a test should
+be located.
+
+1. Does your test depend only on code in ``pd._libs.tslibs``?
+ This test likely belongs in one of:
+
+ - tests.tslibs
+
+ .. note::
+
+ No file in ``tests.tslibs`` should import from any pandas modules
+ outside of ``pd._libs.tslibs``
+
+ - tests.scalar
+ - tests.tseries.offsets
+
+2. Does your test depend only on code in pd._libs?
+ This test likely belongs in one of:
+
+ - tests.libs
+ - tests.groupby.test_libgroupby
+
+3. Is your test for an arithmetic or comparison method?
+ This test likely belongs in one of:
+
+ - tests.arithmetic
+
+ .. note::
+
+ These are intended for tests that can be shared to test the behavior
+ of DataFrame/Series/Index/ExtensionArray using the ``box_with_array``
+ fixture.
+
+ - tests.frame.test_arithmetic
+ - tests.series.test_arithmetic
+
+4. Is your test for a reduction method (min, max, sum, prod, ...)?
+ This test likely belongs in one of:
+
+ - tests.reductions
+
+ .. note::
+
+ These are intended for tests that can be shared to test the behavior
+ of DataFrame/Series/Index/ExtensionArray.
+
+ - tests.frame.test_reductions
+ - tests.series.test_reductions
+ - tests.test_nanops
+
+5. Is your test for an indexing method?
+ This is the most difficult case for deciding where a test belongs, because
+ there are many of these tests, and many of them test more than one method
+ (e.g. both ``Series.__getitem__`` and ``Series.loc.__getitem__``)
+
+ A) Is the test specifically testing an Index method (e.g. ``Index.get_loc``,
+ ``Index.get_indexer``)?
+ This test likely belongs in one of:
+
+ - tests.indexes.test_indexing
+ - tests.indexes.fooindex.test_indexing
+
+ Within that files there should be a method-specific test class e.g.
+ ``TestGetLoc``.
+
+ In most cases, neither ``Series`` nor ``DataFrame`` objects should be
+ needed in these tests.
+
+ B) Is the test for a Series or DataFrame indexing method *other* than
+ ``__getitem__`` or ``__setitem__``, e.g. ``xs``, ``where``, ``take``,
+ ``mask``, ``lookup``, or ``insert``?
+ This test likely belongs in one of:
+
+ - tests.frame.indexing.test_methodname
+ - tests.series.indexing.test_methodname
+
+ C) Is the test for any of ``loc``, ``iloc``, ``at``, or ``iat``?
+ This test likely belongs in one of:
+
+ - tests.indexing.test_loc
+ - tests.indexing.test_iloc
+ - tests.indexing.test_at
+ - tests.indexing.test_iat
+
+ Within the appropriate file, test classes correspond to either types of
+ indexers (e.g. ``TestLocBooleanMask``) or major use cases
+ (e.g. ``TestLocSetitemWithExpansion``).
+
+ See the note in section D) about tests that test multiple indexing methods.
+
+ D) Is the test for ``Series.__getitem__``, ``Series.__setitem__``,
+ ``DataFrame.__getitem__``, or ``DataFrame.__setitem__``?
+ This test likely belongs in one of:
+
+ - tests.series.test_getitem
+ - tests.series.test_setitem
+ - tests.frame.test_getitem
+ - tests.frame.test_setitem
+
+ If many cases such a test may test multiple similar methods, e.g.
+
+ .. code-block:: python
+
+ import pandas as pd
+ import pandas._testing as tm
+
+ def test_getitem_listlike_of_ints():
+ ser = pd.Series(range(5))
+
+ result = ser[[3, 4]]
+ expected = pd.Series([2, 3])
+ tm.assert_series_equal(result, expected)
+
+ result = ser.loc[[3, 4]]
+ tm.assert_series_equal(result, expected)
+
+ In cases like this, the test location should be based on the *underlying*
+ method being tested. Or in the case of a test for a bugfix, the location
+ of the actual bug. So in this example, we know that ``Series.__getitem__``
+ calls ``Series.loc.__getitem__``, so this is *really* a test for
+ ``loc.__getitem__``. So this test belongs in ``tests.indexing.test_loc``.
+
+6. Is your test for a DataFrame or Series method?
+
+ A) Is the method a plotting method?
+ This test likely belongs in one of:
+
+ - tests.plotting
+
+ B) Is the method an IO method?
+ This test likely belongs in one of:
+
+ - tests.io
+
+ C) Otherwise
+ This test likely belongs in one of:
+
+ - tests.series.methods.test_mymethod
+ - tests.frame.methods.test_mymethod
+
+ .. note::
+
+ If a test can be shared between DataFrame/Series using the
+ ``frame_or_series`` fixture, by convention it goes in the
+ ``tests.frame`` file.
+
+ - tests.generic.methods.test_mymethod
+
+ .. note::
+
+ The generic/methods/ directory is only for methods with tests
+ that are fully parametrized over Series/DataFrame
+
+7. Is your test for an Index method, not depending on Series/DataFrame?
+ This test likely belongs in one of:
+
+ - tests.indexes
+
+8) Is your test for one of the pandas-provided ExtensionArrays (``Categorical``,
+ ``DatetimeArray``, ``TimedeltaArray``, ``PeriodArray``, ``IntervalArray``,
+ ``PandasArray``, ``FloatArray``, ``BoolArray``, ``StringArray``)?
+ This test likely belongs in one of:
+
+ - tests.arrays
+
+9) Is your test for *all* ExtensionArray subclasses (the "EA Interface")?
+ This test likely belongs in one of:
+
+ - tests.extension
| Retry of #37637, reverted by #37756 | https://api.github.com/repos/pandas-dev/pandas/pulls/37760 | 2020-11-11T15:38:45Z | 2020-11-14T02:56:11Z | 2020-11-14T02:56:11Z | 2020-11-14T03:00:21Z |
Revert "DOC: test organization" | diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst
index e842c827b417f..f8a6bb6deb52d 100644
--- a/doc/source/development/index.rst
+++ b/doc/source/development/index.rst
@@ -16,7 +16,6 @@ Development
code_style
maintaining
internals
- test_writing
extending
developer
policies
diff --git a/doc/source/development/test_writing.rst b/doc/source/development/test_writing.rst
deleted file mode 100644
index 27d0f44f75633..0000000000000
--- a/doc/source/development/test_writing.rst
+++ /dev/null
@@ -1,147 +0,0 @@
-.. _test_organization:
-
-Test organization
-=================
-Ideally, there should be one, and only one, obvious place for a test to reside.
-Until we reach that ideal, these are some rules of thumb for where a test should
-be located.
-
-1. Does your test depend only on code in ``pd._libs.tslibs``?
-This test likely belongs in one of:
-
- - tests.tslibs
-
- .. note::
-
- No file in ``tests.tslibs`` should import from any pandas modules outside of ``pd._libs.tslibs``
-
- - tests.scalar
- - tests.tseries.offsets
-
-2. Does your test depend only on code in pd._libs?
-This test likely belongs in one of:
-
- - tests.libs
- - tests.groupby.test_libgroupby
-
-3. Is your test for an arithmetic or comparison method?
-This test likely belongs in one of:
-
- - tests.arithmetic
-
- .. note::
-
- These are intended for tests that can be shared to test the behavior of DataFrame/Series/Index/ExtensionArray using the ``box_with_array`` fixture.
-
- - tests.frame.test_arithmetic
- - tests.series.test_arithmetic
-
-4. Is your test for a reduction method (min, max, sum, prod, ...)?
-This test likely belongs in one of:
-
- - tests.reductions
-
- .. note::
-
- These are intended for tests that can be shared to test the behavior of DataFrame/Series/Index/ExtensionArray.
-
- - tests.frame.test_reductions
- - tests.series.test_reductions
- - tests.test_nanops
-
-5. Is your test for an indexing method?
- This is the most difficult case for deciding where a test belongs, because
- there are many of these tests, and many of them test more than one method
- (e.g. both ``Series.__getitem__`` and ``Series.loc.__getitem__``)
-
- A) Is the test specifically testing an Index method (e.g. ``Index.get_loc``, ``Index.get_indexer``)?
- This test likely belongs in one of:
- - tests.indexes.test_indexing
- - tests.indexes.fooindex.test_indexing
-
- Within that files there should be a method-specific test class e.g. ``TestGetLoc``.
-
- In most cases, neither ``Series`` nor ``DataFrame`` objects should be needed in these tests.
-
- B) Is the test for a Series or DataFrame indexing method *other* than ``__getitem__`` or ``__setitem__``, e.g. ``xs``, ``where``, ``take``, ``mask``, ``lookup``, or ``insert``?
- This test likely belongs in one of:
- - tests.frame.indexing.test_methodname
- - tests.series.indexing.test_methodname
-
- C) Is the test for any of ``loc``, ``iloc``, ``at``, or ``iat``?
- This test likely belongs in one of:
- - tests.indexing.test_loc
- - tests.indexing.test_iloc
- - tests.indexing.test_at
- - tests.indexing.test_iat
-
- Within the appropriate file, test classes correspond to either types of indexers (e.g. ``TestLocBooleanMask``) or major use cases (e.g. ``TestLocSetitemWithExpansion``).
-
- See the note in section D) about tests that test multiple indexing methods.
-
- D) Is the test for ``Series.__getitem__``, ``Series.__setitem__``, ``DataFrame.__getitem__``, or ``DataFrame.__setitem__``?
- This test likely belongs in one of:
- - tests.series.test_getitem
- - tests.series.test_setitem
- - tests.frame.test_getitem
- - tests.frame.test_setitem
-
- If many cases such a test may test multiple similar methods, e.g.
-
- .. code-block:: python
- import pandas as pd
- import pandas._testing as tm
-
- def test_getitem_listlike_of_ints():
- ser = pd.Series(range(5))
-
- result = ser[[3, 4]]
- expected = pd.Series([2, 3])
- tm.assert_series_equal(result, expected)
-
- result = ser.loc[[3, 4]]
- tm.assert_series_equal(result, expected)
-
- In cases like this, the test location should be based on the *underlying* method being tested. Or in the case of a test for a bugfix, the location of the actual bug. So in this example, we know that ``Series.__getitem__`` calls ``Series.loc.__getitem__``, so this is *really* a test for ``loc.__getitem__``. So this test belongs in ``tests.indexing.test_loc``
-
-6. Is your test for a DataFrame or Series method?
- A) Is the method a plotting method?
- This test likely belongs in one of:
-
- - tests.plotting
-
- B) Is the method an IO method?
- This test likely belongs in one of:
-
- - tests.io
-
- C) Otherwise
- This test likely belongs in one of:
-
- - tests.series.methods.test_mymethod
- - tests.frame.methods.test_mymethod
-
- .. note::
-
- If a test can be shared between DataFrame/Series using the ``frame_or_series`` fixture, by convention it goes in tests.frame file.
-
- - tests.generic.methods.test_mymethod
-
- .. note::
-
- The generic/methods/ directory is only for methods with tests that are fully parametrized over Series/DataFrame
-
-7. Is your test for an Index method, not depending on Series/DataFrame?
-This test likely belongs in one of:
-
- - tests.indexes
-
-8) Is your test for one of the pandas-provided ExtensionArrays (Categorical, DatetimeArray, TimedeltaArray, PeriodArray, IntervalArray, PandasArray, FloatArray, BoolArray, IntervalArray, StringArray)?
-This test likely belongs in one of:
-
- - tests.arrays
-
-9) Is your test for *all* ExtensionArray subclasses (the "EA Interface")?
-This test likely belongs in one of:
-
- - tests.extension
diff --git a/pandas/tests/series/methods/test_item.py b/pandas/tests/series/methods/test_item.py
index 90e8f6d39c5cc..a7ddc0c22dcf4 100644
--- a/pandas/tests/series/methods/test_item.py
+++ b/pandas/tests/series/methods/test_item.py
@@ -1,7 +1,3 @@
-"""
-Series.item method, mainly testing that we get python scalars as opposed to
-numpy scalars.
-"""
import pytest
from pandas import Series, Timedelta, Timestamp, date_range
@@ -9,7 +5,6 @@
class TestItem:
def test_item(self):
- # We are testing that we get python scalars as opposed to numpy scalars
ser = Series([1])
result = ser.item()
assert result == 1
| Reverts pandas-dev/pandas#37637
(CI is failing because of this) | https://api.github.com/repos/pandas-dev/pandas/pulls/37756 | 2020-11-11T09:20:56Z | 2020-11-11T11:49:37Z | 2020-11-11T11:49:37Z | 2020-11-11T11:49:41Z |
ENH: support Ellipsis in loc/iloc | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index b7efec8fd2e89..bd92c9890c0b8 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -148,11 +148,13 @@ Other enhancements
- Methods that relied on hashmap based algos such as :meth:`DataFrameGroupBy.value_counts`, :meth:`DataFrameGroupBy.count` and :func:`factorize` ignored imaginary component for complex numbers (:issue:`17927`)
- Add :meth:`Series.str.removeprefix` and :meth:`Series.str.removesuffix` introduced in Python 3.9 to remove pre-/suffixes from string-type :class:`Series` (:issue:`36944`)
- Attempting to write into a file in missing parent directory with :meth:`DataFrame.to_csv`, :meth:`DataFrame.to_html`, :meth:`DataFrame.to_excel`, :meth:`DataFrame.to_feather`, :meth:`DataFrame.to_parquet`, :meth:`DataFrame.to_stata`, :meth:`DataFrame.to_json`, :meth:`DataFrame.to_pickle`, and :meth:`DataFrame.to_xml` now explicitly mentions missing parent directory, the same is true for :class:`Series` counterparts (:issue:`24306`)
+- Indexing with ``.loc`` and ``.iloc`` now supports ``Ellipsis`` (:issue:`37750`)
- :meth:`IntegerArray.all` , :meth:`IntegerArray.any`, :meth:`FloatingArray.any`, and :meth:`FloatingArray.all` use Kleene logic (:issue:`41967`)
- Added support for nullable boolean and integer types in :meth:`DataFrame.to_stata`, :class:`~pandas.io.stata.StataWriter`, :class:`~pandas.io.stata.StataWriter117`, and :class:`~pandas.io.stata.StataWriterUTF8` (:issue:`40855`)
- :meth:`DataFrame.__pos__`, :meth:`DataFrame.__neg__` now retain ``ExtensionDtype`` dtypes (:issue:`43883`)
- The error raised when an optional dependency can't be imported now includes the original exception, for easier investigation (:issue:`43882`)
- Added :meth:`.ExponentialMovingWindow.sum` (:issue:`13297`)
+-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 7b0d163c659a5..e2f1a2d6a1e23 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3254,6 +3254,11 @@ def get_locs(self, seq):
# entry in `seq`
indexer = Index(np.arange(n))
+ if any(x is Ellipsis for x in seq):
+ raise NotImplementedError(
+ "MultiIndex does not support indexing with Ellipsis"
+ )
+
def _convert_to_indexer(r) -> Int64Index:
# return an indexer
if isinstance(r, slice):
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index bbb3cb3391dfa..918a9ea1b8030 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -3,9 +3,7 @@
from contextlib import suppress
from typing import (
TYPE_CHECKING,
- Any,
Hashable,
- Sequence,
)
import warnings
@@ -67,6 +65,7 @@
# "null slice"
_NS = slice(None, None)
+_one_ellipsis_message = "indexer may only contain one '...' entry"
# the public IndexSlicerMaker
@@ -731,11 +730,33 @@ def _validate_key(self, key, axis: int):
"""
raise AbstractMethodError(self)
- def _has_valid_tuple(self, key: tuple):
+ def _expand_ellipsis(self, tup: tuple) -> tuple:
+ """
+ If a tuple key includes an Ellipsis, replace it with an appropriate
+ number of null slices.
+ """
+ if any(x is Ellipsis for x in tup):
+ if tup.count(Ellipsis) > 1:
+ raise IndexingError(_one_ellipsis_message)
+
+ if len(tup) == self.ndim:
+ # It is unambiguous what axis this Ellipsis is indexing,
+ # treat as a single null slice.
+ i = tup.index(Ellipsis)
+ # FIXME: this assumes only one Ellipsis
+ new_key = tup[:i] + (_NS,) + tup[i + 1 :]
+ return new_key
+
+ # TODO: other cases? only one test gets here, and that is covered
+ # by _validate_key_length
+ return tup
+
+ def _validate_tuple_indexer(self, key: tuple) -> tuple:
"""
Check the key for valid keys across my indexer.
"""
- self._validate_key_length(key)
+ key = self._validate_key_length(key)
+ key = self._expand_ellipsis(key)
for i, k in enumerate(key):
try:
self._validate_key(k, i)
@@ -744,6 +765,7 @@ def _has_valid_tuple(self, key: tuple):
"Location based indexing can only have "
f"[{self._valid_types}] types"
) from err
+ return key
def _is_nested_tuple_indexer(self, tup: tuple) -> bool:
"""
@@ -772,9 +794,16 @@ def _convert_tuple(self, key):
return tuple(keyidx)
- def _validate_key_length(self, key: Sequence[Any]) -> None:
+ def _validate_key_length(self, key: tuple) -> tuple:
if len(key) > self.ndim:
+ if key[0] is Ellipsis:
+ # e.g. Series.iloc[..., 3] reduces to just Series.iloc[3]
+ key = key[1:]
+ if Ellipsis in key:
+ raise IndexingError(_one_ellipsis_message)
+ return self._validate_key_length(key)
raise IndexingError("Too many indexers")
+ return key
def _getitem_tuple_same_dim(self, tup: tuple):
"""
@@ -822,7 +851,7 @@ def _getitem_lowerdim(self, tup: tuple):
with suppress(IndexingError):
return self._handle_lowerdim_multi_index_axis0(tup)
- self._validate_key_length(tup)
+ tup = self._validate_key_length(tup)
for i, key in enumerate(tup):
if is_label_like(key):
@@ -1093,10 +1122,11 @@ def _getitem_iterable(self, key, axis: int):
def _getitem_tuple(self, tup: tuple):
with suppress(IndexingError):
+ tup = self._expand_ellipsis(tup)
return self._getitem_lowerdim(tup)
# no multi-index, so validate all of the indexers
- self._has_valid_tuple(tup)
+ tup = self._validate_tuple_indexer(tup)
# ugly hack for GH #836
if self._multi_take_opportunity(tup):
@@ -1126,6 +1156,8 @@ def _getitem_axis(self, key, axis: int):
key = item_from_zerodim(key)
if is_iterator(key):
key = list(key)
+ if key is Ellipsis:
+ key = slice(None)
labels = self.obj._get_axis(axis)
@@ -1409,7 +1441,7 @@ def _validate_integer(self, key: int, axis: int) -> None:
def _getitem_tuple(self, tup: tuple):
- self._has_valid_tuple(tup)
+ tup = self._validate_tuple_indexer(tup)
with suppress(IndexingError):
return self._getitem_lowerdim(tup)
@@ -1439,7 +1471,9 @@ def _get_list_axis(self, key, axis: int):
raise IndexError("positional indexers are out-of-bounds") from err
def _getitem_axis(self, key, axis: int):
- if isinstance(key, ABCDataFrame):
+ if key is Ellipsis:
+ key = slice(None)
+ elif isinstance(key, ABCDataFrame):
raise IndexError(
"DataFrame indexer is not allowed for .iloc\n"
"Consider using .loc for automatic alignment."
@@ -2381,7 +2415,11 @@ def is_label_like(key) -> bool:
bool
"""
# select a label or row
- return not isinstance(key, slice) and not is_list_like_indexer(key)
+ return (
+ not isinstance(key, slice)
+ and not is_list_like_indexer(key)
+ and key is not Ellipsis
+ )
def need_slice(obj: slice) -> bool:
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 25c0625d1d790..94ecfe81abd45 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -37,6 +37,10 @@
import pandas._testing as tm
from pandas.api.types import is_scalar
from pandas.core.api import Float64Index
+from pandas.core.indexing import (
+ IndexingError,
+ _one_ellipsis_message,
+)
from pandas.tests.indexing.common import Base
@@ -1524,6 +1528,66 @@ def test_loc_setitem_cast3(self):
assert df.dtypes.one == np.dtype(np.int8)
+class TestLocWithEllipsis:
+ @pytest.fixture(params=[tm.loc, tm.iloc])
+ def indexer(self, request):
+ # Test iloc while we're here
+ return request.param
+
+ @pytest.fixture
+ def obj(self, series_with_simple_index, frame_or_series):
+ obj = series_with_simple_index
+ if frame_or_series is not Series:
+ obj = obj.to_frame()
+ return obj
+
+ def test_loc_iloc_getitem_ellipsis(self, obj, indexer):
+ result = indexer(obj)[...]
+ tm.assert_equal(result, obj)
+
+ def test_loc_iloc_getitem_leading_ellipses(self, series_with_simple_index, indexer):
+ obj = series_with_simple_index
+ key = 0 if (indexer is tm.iloc or len(obj) == 0) else obj.index[0]
+
+ if indexer is tm.loc and obj.index.is_boolean():
+ # passing [False] will get interpreted as a boolean mask
+ # TODO: should it? unambiguous when lengths dont match?
+ return
+ if indexer is tm.loc and isinstance(obj.index, MultiIndex):
+ msg = "MultiIndex does not support indexing with Ellipsis"
+ with pytest.raises(NotImplementedError, match=msg):
+ result = indexer(obj)[..., [key]]
+
+ elif len(obj) != 0:
+ result = indexer(obj)[..., [key]]
+ expected = indexer(obj)[[key]]
+ tm.assert_series_equal(result, expected)
+
+ key2 = 0 if indexer is tm.iloc else obj.name
+ df = obj.to_frame()
+ result = indexer(df)[..., [key2]]
+ expected = indexer(df)[:, [key2]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_loc_iloc_getitem_ellipses_only_one_ellipsis(self, obj, indexer):
+ # GH37750
+ key = 0 if (indexer is tm.iloc or len(obj) == 0) else obj.index[0]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., ...]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., [key], ...]
+
+ with pytest.raises(IndexingError, match=_one_ellipsis_message):
+ indexer(obj)[..., ..., key]
+
+ # one_ellipsis_message takes precedence over "Too many indexers"
+ # only when the first key is Ellipsis
+ with pytest.raises(IndexingError, match="Too many indexers"):
+ indexer(obj)[key, ..., ...]
+
+
class TestLocWithMultiIndex:
@pytest.mark.parametrize(
"keys, expected",
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
closes #10956 | https://api.github.com/repos/pandas-dev/pandas/pulls/37750 | 2020-11-10T22:48:24Z | 2021-10-16T14:47:43Z | 2021-10-16T14:47:43Z | 2021-10-16T15:14:09Z |
CLN: remove unused min_count argument in libgroupby.group_nth | diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 5a958d5e0bd3c..438d9fa625737 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -986,8 +986,8 @@ def group_last(rank_t[:, :] out,
def group_nth(rank_t[:, :] out,
int64_t[:] counts,
ndarray[rank_t, ndim=2] values,
- const int64_t[:] labels, int64_t rank=1,
- Py_ssize_t min_count=-1):
+ const int64_t[:] labels, int64_t rank=1
+ ):
"""
Only aggregates on axis=0
"""
@@ -998,8 +998,6 @@ def group_nth(rank_t[:, :] out,
ndarray[int64_t, ndim=2] nobs
bint runtime_error = False
- assert min_count == -1, "'min_count' only used in add and prod"
-
# TODO(cython 3.0):
# Instead of `labels.shape[0]` use `len(labels)`
if not len(values) == labels.shape[0]:
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 438030008bb4d..fc80852f00c95 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -603,8 +603,7 @@ def _aggregate(
):
if agg_func is libgroupby.group_nth:
# different signature from the others
- # TODO: should we be using min_count instead of hard-coding it?
- agg_func(result, counts, values, comp_ids, rank=1, min_count=-1)
+ agg_func(result, counts, values, comp_ids, rank=1)
else:
agg_func(result, counts, values, comp_ids, min_count)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37747 | 2020-11-10T19:51:16Z | 2020-11-13T05:03:24Z | 2020-11-13T05:03:24Z | 2020-11-13T05:03:27Z |
CI: troubleshoot windows builds | diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index 9b553fbc81a03..78d24c814840a 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -25,7 +25,7 @@ PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s
if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then
# GH#37455 windows py38 build appears to be running out of memory
# skip collection of window tests
- PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/window/"
+ PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/window/ --ignore=pandas/tests/plotting/"
fi
echo $PYTEST_CMD
diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py
index 805a284c8f863..7ed29507fe0f4 100644
--- a/pandas/tests/plotting/test_groupby.py
+++ b/pandas/tests/plotting/test_groupby.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas.compat import PY38, is_platform_windows
+from pandas.compat import is_platform_windows
import pandas.util._test_decorators as td
from pandas import DataFrame, Index, Series
@@ -15,7 +15,7 @@
@td.skip_if_no_mpl
class TestDataFrameGroupByPlots(TestPlotBase):
@pytest.mark.xfail(
- is_platform_windows() and not PY38,
+ is_platform_windows(),
reason="Looks like LinePlot._is_ts_plot is wrong",
strict=False,
)
| Windows builds are still hitting what look like OOM errors. Trying splitting these into smaller pieces; its fragile. | https://api.github.com/repos/pandas-dev/pandas/pulls/37746 | 2020-11-10T18:08:19Z | 2020-11-18T13:55:20Z | 2020-11-18T13:55:20Z | 2020-11-18T16:27:54Z |
TYP: follow-up to #37723 | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index d9e51810f1445..d38974839394d 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -367,14 +367,21 @@ def _wrap_results(result, dtype: np.dtype, fill_value=None):
return result
-def _datetimelike_compat(func):
+def _datetimelike_compat(func: F) -> F:
"""
If we have datetime64 or timedelta64 values, ensure we have a correct
mask before calling the wrapped function, then cast back afterwards.
"""
@functools.wraps(func)
- def new_func(values, *, axis=None, skipna=True, mask=None, **kwargs):
+ def new_func(
+ values: np.ndarray,
+ *,
+ axis: Optional[int] = None,
+ skipna: bool = True,
+ mask: Optional[np.ndarray] = None,
+ **kwargs,
+ ):
orig_values = values
datetimelike = values.dtype.kind in ["m", "M"]
@@ -390,7 +397,7 @@ def new_func(values, *, axis=None, skipna=True, mask=None, **kwargs):
return result
- return new_func
+ return cast(F, new_func)
def _na_for_min_count(
| - [ ] 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/37745 | 2020-11-10T17:37:34Z | 2020-11-11T17:12:32Z | 2020-11-11T17:12:32Z | 2020-11-11T17:12:46Z |
DOC: add hvplot | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 670905f6587bc..723adf36dbe9a 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -178,6 +178,16 @@ D-Tale integrates seamlessly with jupyter notebooks, python terminals, kaggle
& Google Colab. Here are some demos of the `grid <http://alphatechadmin.pythonanywhere.com/>`__
and `chart-builder <http://alphatechadmin.pythonanywhere.com/charts/4?chart_type=surface&query=&x=date&z=Col0&agg=raw&cpg=false&y=%5B%22security_id%22%5D>`__.
+`hvplot <https://hvplot.holoviz.org/index.html>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+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
+
+.. code:: python
+
+ pd.set_option("plotting.backend", "hvplot")
+
.. _ecosystem.ide:
IDE
| - [x] closes #33730
- [NA] tests added / passed
- [NA] passes `black pandas`
- [NA] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [NA?] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37744 | 2020-11-10T16:50:25Z | 2020-11-17T22:37:28Z | 2020-11-17T22:37:28Z | 2020-11-17T22:37:44Z |
Backport PR #37661 on branch 1.1.x: BUG: RollingGroupby when groupby key is in the index | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index e0fa68e3b9f80..a29ae1912e338 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -25,6 +25,7 @@ Bug fixes
~~~~~~~~~
- Bug in metadata propagation for ``groupby`` iterator (:issue:`37343`)
- Bug in indexing on a :class:`Series` with ``CategoricalDtype`` after unpickling (:issue:`37631`)
+- Bug in :class:`RollingGroupby` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 617c43e0a59ed..ce7281988e105 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -2193,20 +2193,39 @@ def _apply(
use_numba_cache,
**kwargs,
)
- # Cannot use _wrap_outputs because we calculate the result all at once
- # Compose MultiIndex result from grouping levels then rolling level
- # Aggregate the MultiIndex data as tuples then the level names
- grouped_object_index = self.obj.index
- grouped_index_name = [*grouped_object_index.names]
- groupby_keys = [grouping.name for grouping in self._groupby.grouper._groupings]
- result_index_names = groupby_keys + grouped_index_name
+ # Reconstruct the resulting MultiIndex from tuples
+ # 1st set of levels = group by labels
+ # 2nd set of levels = original index
+ # Ignore 2nd set of levels if a group by label include an index level
+ result_index_names = [
+ grouping.name for grouping in self._groupby.grouper._groupings
+ ]
+ grouped_object_index = None
+
+ column_keys = [
+ key
+ for key in result_index_names
+ if key not in self.obj.index.names or key is None
+ ]
+
+ if len(column_keys) == len(result_index_names):
+ grouped_object_index = self.obj.index
+ grouped_index_name = [*grouped_object_index.names]
+ result_index_names += grouped_index_name
+ else:
+ # Our result will have still kept the column in the result
+ result = result.drop(columns=column_keys, errors="ignore")
result_index_data = []
for key, values in self._groupby.grouper.indices.items():
for value in values:
data = [
*com.maybe_make_list(key),
- *com.maybe_make_list(grouped_object_index[value]),
+ *com.maybe_make_list(
+ grouped_object_index[value]
+ if grouped_object_index is not None
+ else []
+ ),
]
result_index_data.append(tuple(data))
diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py
index 493a844ca7a44..da31fbaddc6e4 100644
--- a/pandas/tests/window/test_grouper.py
+++ b/pandas/tests/window/test_grouper.py
@@ -2,7 +2,7 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import DataFrame, MultiIndex, Series
import pandas._testing as tm
from pandas.core.groupby.groupby import get_groupby
@@ -449,3 +449,33 @@ def test_groupby_rolling_no_sort(self):
index=pd.MultiIndex.from_tuples([(2, 0), (1, 1)], names=["foo", None]),
)
tm.assert_frame_equal(result, expected)
+
+ def test_groupby_rolling_group_keys(self):
+ # GH 37641
+ arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]]
+ index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2"))
+
+ s = Series([1, 2, 3], index=index)
+ result = s.groupby(["idx1", "idx2"], group_keys=False).rolling(1).mean()
+ expected = Series(
+ [1.0, 2.0, 3.0],
+ index=MultiIndex.from_tuples(
+ [("val1", "val1"), ("val1", "val1"), ("val2", "val2")],
+ names=["idx1", "idx2"],
+ ),
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_groupby_rolling_index_level_and_column_label(self):
+ arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]]
+ index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2"))
+
+ df = DataFrame({"A": [1, 1, 2], "B": range(3)}, index=index)
+ result = df.groupby(["idx1", "A"]).rolling(1).mean()
+ expected = DataFrame(
+ {"B": [0.0, 1.0, 2.0]},
+ index=MultiIndex.from_tuples(
+ [("val1", 1), ("val1", 1), ("val2", 2)], names=["idx1", "A"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
| Backport PR #37661 | https://api.github.com/repos/pandas-dev/pandas/pulls/37741 | 2020-11-10T13:39:47Z | 2020-11-10T14:52:29Z | 2020-11-10T14:52:29Z | 2020-11-10T14:52:34Z |
TYP: fix mypy ignored err in pandas/io/formats/format.py | diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 5b69ef4eba26e..e4bd1eddbc5f8 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1046,12 +1046,14 @@ def to_csv(
"""
from pandas.io.formats.csvs import CSVFormatter
- created_buffer = path_or_buf is None
- if created_buffer:
+ if path_or_buf is None:
+ created_buffer = True
path_or_buf = StringIO()
+ else:
+ created_buffer = False
csv_formatter = CSVFormatter(
- path_or_buf=path_or_buf, # type: ignore[arg-type]
+ path_or_buf=path_or_buf,
line_terminator=line_terminator,
sep=sep,
encoding=encoding,
| - [ ] xref #37715
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Handle ignored mypy error in ``pandas/io/formats/format.py`` | https://api.github.com/repos/pandas-dev/pandas/pulls/37739 | 2020-11-10T10:57:12Z | 2020-11-10T19:22:44Z | 2020-11-10T19:22:43Z | 2020-12-03T07:57:38Z |
TYP: fix mypy ignored error in pandas/io/formats/latex.py | diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py
index f3c49e1cd3801..0212fd6f695cb 100644
--- a/pandas/io/formats/latex.py
+++ b/pandas/io/formats/latex.py
@@ -2,7 +2,7 @@
Module for formatting output data in Latex.
"""
from abc import ABC, abstractmethod
-from typing import Iterator, List, Optional, Tuple, Type, Union
+from typing import Iterator, List, Optional, Sequence, Tuple, Type, Union
import numpy as np
@@ -74,9 +74,7 @@ def __init__(
self.multirow = multirow
self.clinebuf: List[List[int]] = []
self.strcols = self._get_strcols()
- self.strrows: List[List[str]] = list(
- zip(*self.strcols) # type: ignore[arg-type]
- )
+ self.strrows = list(zip(*self.strcols))
def get_strrow(self, row_num: int) -> str:
"""Get string representation of the row."""
@@ -179,7 +177,7 @@ def _empty_info_line(self):
f"Index: {self.frame.index}"
)
- def _preprocess_row(self, row: List[str]) -> List[str]:
+ def _preprocess_row(self, row: Sequence[str]) -> List[str]:
"""Preprocess elements of the row."""
if self.fmt.escape:
crow = _escape_symbols(row)
@@ -781,7 +779,7 @@ def _get_index_format(self) -> str:
return "l" * self.frame.index.nlevels if self.fmt.index else ""
-def _escape_symbols(row: List[str]) -> List[str]:
+def _escape_symbols(row: Sequence[str]) -> List[str]:
"""Carry out string replacements for special symbols.
Parameters
@@ -813,7 +811,7 @@ def _escape_symbols(row: List[str]) -> List[str]:
]
-def _convert_to_bold(crow: List[str], ilevels: int) -> List[str]:
+def _convert_to_bold(crow: Sequence[str], ilevels: int) -> List[str]:
"""Convert elements in ``crow`` to bold."""
return [
f"\\textbf{{{x}}}" if j < ilevels and x.strip() not in ["", "{}"] else x
| - [ ] xref #37715
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Handle mypy ignored error in ``pandas/io/formats/latex.py``. | https://api.github.com/repos/pandas-dev/pandas/pulls/37738 | 2020-11-10T10:39:33Z | 2020-11-10T14:49:41Z | 2020-11-10T14:49:41Z | 2020-11-10T15:22:54Z |
BUG: read_html - file path cannot be pathlib.Path type | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index e488ca52be8a0..5ffdd959eefbd 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -507,6 +507,7 @@ I/O
- Bug in :class:`HDFStore` was dropping timezone information when exporting :class:`Series` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
- :func:`read_csv` was closing user-provided binary file handles when ``engine="c"`` and an ``encoding`` was requested (:issue:`36980`)
- Bug in :meth:`DataFrame.to_hdf` was not dropping missing rows with ``dropna=True`` (:issue:`35719`)
+- Bug in :func:`read_html` was raising a ``TypeError`` when supplying a ``pathlib.Path`` argument to the ``io`` parameter (:issue:`37705`)
Plotting
^^^^^^^^
diff --git a/pandas/io/html.py b/pandas/io/html.py
index 1534e42d8fb5a..334a3dab6c13a 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -20,7 +20,7 @@
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.frame import DataFrame
-from pandas.io.common import is_url, urlopen, validate_header_arg
+from pandas.io.common import is_url, stringify_path, urlopen, validate_header_arg
from pandas.io.formats.printing import pprint_thing
from pandas.io.parsers import TextParser
@@ -1080,6 +1080,9 @@ def read_html(
"data (you passed a negative value)"
)
validate_header_arg(header)
+
+ io = stringify_path(io)
+
return _parse(
flavor=flavor,
io=io,
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index f929d4ac31484..eb704ccf1e594 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -2,6 +2,7 @@
from importlib import reload
from io import BytesIO, StringIO
import os
+from pathlib import Path
import re
import threading
from urllib.error import URLError
@@ -1233,3 +1234,11 @@ def run(self):
while helper_thread1.is_alive() or helper_thread2.is_alive():
pass
assert None is helper_thread1.err is helper_thread2.err
+
+ def test_parse_path_object(self, datapath):
+ # GH 37705
+ file_path_string = datapath("io", "data", "html", "spam.html")
+ file_path = Path(file_path_string)
+ df1 = self.read_html(file_path_string)[0]
+ df2 = self.read_html(file_path)[0]
+ tm.assert_frame_equal(df1, df2)
| Fix `read_html` TypeError when parsing `pathlib.Path` object.
| https://api.github.com/repos/pandas-dev/pandas/pulls/37736 | 2020-11-10T06:47:19Z | 2020-11-11T02:29:56Z | 2020-11-11T02:29:56Z | 2020-11-11T19:20:38Z |
TST: parametrize in tests/plotting/test_frame.py | diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py
index 11a46858ba281..8336d0b25eea3 100644
--- a/pandas/tests/plotting/test_frame.py
+++ b/pandas/tests/plotting/test_frame.py
@@ -190,11 +190,11 @@ def test_color_single_series_list(self):
df = DataFrame({"A": [1, 2, 3]})
_check_plot_works(df.plot, color=["red"])
- def test_rgb_tuple_color(self):
+ @pytest.mark.parametrize("color", [(1, 0, 0), (1, 0, 0, 0.5)])
+ def test_rgb_tuple_color(self, color):
# GH 16695
df = DataFrame({"x": [1, 2], "y": [3, 4]})
- _check_plot_works(df.plot, x="x", y="y", color=(1, 0, 0))
- _check_plot_works(df.plot, x="x", y="y", color=(1, 0, 0, 0.5))
+ _check_plot_works(df.plot, x="x", y="y", color=color)
def test_color_empty_string(self):
df = DataFrame(np.random.randn(10, 2))
@@ -443,11 +443,21 @@ def test_subplots(self):
for ax in axes:
assert ax.get_legend() is None
- def test_groupby_boxplot_sharey(self):
+ @pytest.mark.parametrize(
+ "kwargs, expected",
+ [
+ # behavior without keyword
+ ({}, [True, False, True, False]),
+ # set sharey=True should be identical
+ ({"sharey": True}, [True, False, True, False]),
+ # sharey=False, all yticklabels should be visible
+ ({"sharey": False}, [True, True, True, True]),
+ ],
+ )
+ def test_groupby_boxplot_sharey(self, kwargs, expected):
# https://github.com/pandas-dev/pandas/issues/20968
# sharey can now be switched check whether the right
# pair of axes is turned on or off
-
df = DataFrame(
{
"a": [-1.43, -0.15, -3.70, -1.43, -0.14],
@@ -456,27 +466,25 @@ def test_groupby_boxplot_sharey(self):
},
index=[0, 1, 2, 3, 4],
)
-
- # behavior without keyword
- axes = df.groupby("c").boxplot()
- expected = [True, False, True, False]
- self._assert_ytickslabels_visibility(axes, expected)
-
- # set sharey=True should be identical
- axes = df.groupby("c").boxplot(sharey=True)
- expected = [True, False, True, False]
- self._assert_ytickslabels_visibility(axes, expected)
-
- # sharey=False, all yticklabels should be visible
- axes = df.groupby("c").boxplot(sharey=False)
- expected = [True, True, True, True]
+ axes = df.groupby("c").boxplot(**kwargs)
self._assert_ytickslabels_visibility(axes, expected)
- def test_groupby_boxplot_sharex(self):
+ @pytest.mark.parametrize(
+ "kwargs, expected",
+ [
+ # behavior without keyword
+ ({}, [True, True, True, True]),
+ # set sharex=False should be identical
+ ({"sharex": False}, [True, True, True, True]),
+ # sharex=True, xticklabels should be visible
+ # only for bottom plots
+ ({"sharex": True}, [False, False, True, True]),
+ ],
+ )
+ def test_groupby_boxplot_sharex(self, kwargs, expected):
# https://github.com/pandas-dev/pandas/issues/20968
# sharex can now be switched check whether the right
# pair of axes is turned on or off
-
df = DataFrame(
{
"a": [-1.43, -0.15, -3.70, -1.43, -0.14],
@@ -485,21 +493,7 @@ def test_groupby_boxplot_sharex(self):
},
index=[0, 1, 2, 3, 4],
)
-
- # behavior without keyword
- axes = df.groupby("c").boxplot()
- expected = [True, True, True, True]
- self._assert_xtickslabels_visibility(axes, expected)
-
- # set sharex=False should be identical
- axes = df.groupby("c").boxplot(sharex=False)
- expected = [True, True, True, True]
- self._assert_xtickslabels_visibility(axes, expected)
-
- # sharex=True, yticklabels should be visible
- # only for bottom plots
- axes = df.groupby("c").boxplot(sharex=True)
- expected = [False, False, True, True]
+ axes = df.groupby("c").boxplot(**kwargs)
self._assert_xtickslabels_visibility(axes, expected)
@pytest.mark.slow
@@ -558,24 +552,12 @@ def test_subplots_timeseries_y_axis(self):
}
testdata = DataFrame(data)
- ax_numeric = testdata.plot(y="numeric")
- assert (
- ax_numeric.get_lines()[0].get_data()[1] == testdata["numeric"].values
- ).all()
- ax_timedelta = testdata.plot(y="timedelta")
- assert (
- ax_timedelta.get_lines()[0].get_data()[1] == testdata["timedelta"].values
- ).all()
- ax_datetime_no_tz = testdata.plot(y="datetime_no_tz")
- assert (
- ax_datetime_no_tz.get_lines()[0].get_data()[1]
- == testdata["datetime_no_tz"].values
- ).all()
- ax_datetime_all_tz = testdata.plot(y="datetime_all_tz")
- assert (
- ax_datetime_all_tz.get_lines()[0].get_data()[1]
- == testdata["datetime_all_tz"].values
- ).all()
+ y_cols = ["numeric", "timedelta", "datetime_no_tz", "datetime_all_tz"]
+ for col in y_cols:
+ ax = testdata.plot(y=col)
+ result = ax.get_lines()[0].get_data()[1]
+ expected = testdata[col].values
+ assert (result == expected).all()
msg = "no numeric data to plot"
with pytest.raises(TypeError, match=msg):
@@ -633,7 +615,7 @@ def test_subplots_timeseries_y_axis_not_supported(self):
).all()
@pytest.mark.slow
- def test_subplots_layout(self):
+ def test_subplots_layout_multi_column(self):
# GH 6667
df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10]))
@@ -666,15 +648,26 @@ def test_subplots_layout(self):
with pytest.raises(ValueError):
df.plot(subplots=True, layout=(-1, -1))
- # single column
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ "kwargs, expected_axes_num, expected_layout, expected_shape",
+ [
+ ({}, 1, (1, 1), (1,)),
+ ({"layout": (3, 3)}, 1, (3, 3), (3, 3)),
+ ],
+ )
+ def test_subplots_layout_single_column(
+ self, kwargs, expected_axes_num, expected_layout, expected_shape
+ ):
+ # GH 6667
df = DataFrame(np.random.rand(10, 1), index=list(string.ascii_letters[:10]))
- axes = df.plot(subplots=True)
- self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
- assert axes.shape == (1,)
-
- axes = df.plot(subplots=True, layout=(3, 3))
- self._check_axes_shape(axes, axes_num=1, layout=(3, 3))
- assert axes.shape == (3, 3)
+ axes = df.plot(subplots=True, **kwargs)
+ self._check_axes_shape(
+ axes,
+ axes_num=expected_axes_num,
+ layout=expected_layout,
+ )
+ assert axes.shape == expected_shape
@pytest.mark.slow
def test_subplots_warnings(self):
@@ -1066,24 +1059,20 @@ def test_bar_barwidth(self):
assert r.get_height() == width
@pytest.mark.slow
- def test_bar_barwidth_position(self):
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"kind": "bar", "stacked": False},
+ {"kind": "bar", "stacked": True},
+ {"kind": "barh", "stacked": False},
+ {"kind": "barh", "stacked": True},
+ {"kind": "bar", "subplots": True},
+ {"kind": "barh", "subplots": True},
+ ],
+ )
+ def test_bar_barwidth_position(self, kwargs):
df = DataFrame(np.random.randn(5, 5))
- self._check_bar_alignment(
- df, kind="bar", stacked=False, width=0.9, position=0.2
- )
- self._check_bar_alignment(df, kind="bar", stacked=True, width=0.9, position=0.2)
- self._check_bar_alignment(
- df, kind="barh", stacked=False, width=0.9, position=0.2
- )
- self._check_bar_alignment(
- df, kind="barh", stacked=True, width=0.9, position=0.2
- )
- self._check_bar_alignment(
- df, kind="bar", subplots=True, width=0.9, position=0.2
- )
- self._check_bar_alignment(
- df, kind="barh", subplots=True, width=0.9, position=0.2
- )
+ self._check_bar_alignment(df, width=0.9, position=0.2, **kwargs)
@pytest.mark.slow
def test_bar_barwidth_position_int(self):
@@ -1503,68 +1492,59 @@ def _check_bar_alignment(
return axes
@pytest.mark.slow
- def test_bar_stacked_center(self):
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ # stacked center
+ dict(kind="bar", stacked=True),
+ dict(kind="bar", stacked=True, width=0.9),
+ dict(kind="barh", stacked=True),
+ dict(kind="barh", stacked=True, width=0.9),
+ # center
+ dict(kind="bar", stacked=False),
+ dict(kind="bar", stacked=False, width=0.9),
+ dict(kind="barh", stacked=False),
+ dict(kind="barh", stacked=False, width=0.9),
+ # subplots center
+ dict(kind="bar", subplots=True),
+ dict(kind="bar", subplots=True, width=0.9),
+ dict(kind="barh", subplots=True),
+ dict(kind="barh", subplots=True, width=0.9),
+ # align edge
+ dict(kind="bar", stacked=True, align="edge"),
+ dict(kind="bar", stacked=True, width=0.9, align="edge"),
+ dict(kind="barh", stacked=True, align="edge"),
+ dict(kind="barh", stacked=True, width=0.9, align="edge"),
+ dict(kind="bar", stacked=False, align="edge"),
+ dict(kind="bar", stacked=False, width=0.9, align="edge"),
+ dict(kind="barh", stacked=False, align="edge"),
+ dict(kind="barh", stacked=False, width=0.9, align="edge"),
+ dict(kind="bar", subplots=True, align="edge"),
+ dict(kind="bar", subplots=True, width=0.9, align="edge"),
+ dict(kind="barh", subplots=True, align="edge"),
+ dict(kind="barh", subplots=True, width=0.9, align="edge"),
+ ],
+ )
+ def test_bar_align_multiple_columns(self, kwargs):
# GH2157
df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5))
- self._check_bar_alignment(df, kind="bar", stacked=True)
- self._check_bar_alignment(df, kind="bar", stacked=True, width=0.9)
- self._check_bar_alignment(df, kind="barh", stacked=True)
- self._check_bar_alignment(df, kind="barh", stacked=True, width=0.9)
-
- @pytest.mark.slow
- def test_bar_center(self):
- df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5))
- self._check_bar_alignment(df, kind="bar", stacked=False)
- self._check_bar_alignment(df, kind="bar", stacked=False, width=0.9)
- self._check_bar_alignment(df, kind="barh", stacked=False)
- self._check_bar_alignment(df, kind="barh", stacked=False, width=0.9)
+ self._check_bar_alignment(df, **kwargs)
@pytest.mark.slow
- def test_bar_subplots_center(self):
- df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5))
- self._check_bar_alignment(df, kind="bar", subplots=True)
- self._check_bar_alignment(df, kind="bar", subplots=True, width=0.9)
- self._check_bar_alignment(df, kind="barh", subplots=True)
- self._check_bar_alignment(df, kind="barh", subplots=True, width=0.9)
-
- @pytest.mark.slow
- def test_bar_align_single_column(self):
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ dict(kind="bar", stacked=False),
+ dict(kind="bar", stacked=True),
+ dict(kind="barh", stacked=False),
+ dict(kind="barh", stacked=True),
+ dict(kind="bar", subplots=True),
+ dict(kind="barh", subplots=True),
+ ],
+ )
+ def test_bar_align_single_column(self, kwargs):
df = DataFrame(np.random.randn(5))
- self._check_bar_alignment(df, kind="bar", stacked=False)
- self._check_bar_alignment(df, kind="bar", stacked=True)
- self._check_bar_alignment(df, kind="barh", stacked=False)
- self._check_bar_alignment(df, kind="barh", stacked=True)
- self._check_bar_alignment(df, kind="bar", subplots=True)
- self._check_bar_alignment(df, kind="barh", subplots=True)
-
- @pytest.mark.slow
- def test_bar_edge(self):
- df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5))
-
- self._check_bar_alignment(df, kind="bar", stacked=True, align="edge")
- self._check_bar_alignment(df, kind="bar", stacked=True, width=0.9, align="edge")
- self._check_bar_alignment(df, kind="barh", stacked=True, align="edge")
- self._check_bar_alignment(
- df, kind="barh", stacked=True, width=0.9, align="edge"
- )
-
- self._check_bar_alignment(df, kind="bar", stacked=False, align="edge")
- self._check_bar_alignment(
- df, kind="bar", stacked=False, width=0.9, align="edge"
- )
- self._check_bar_alignment(df, kind="barh", stacked=False, align="edge")
- self._check_bar_alignment(
- df, kind="barh", stacked=False, width=0.9, align="edge"
- )
-
- self._check_bar_alignment(df, kind="bar", subplots=True, align="edge")
- self._check_bar_alignment(
- df, kind="bar", subplots=True, width=0.9, align="edge"
- )
- self._check_bar_alignment(df, kind="barh", subplots=True, align="edge")
- self._check_bar_alignment(
- df, kind="barh", subplots=True, width=0.9, align="edge"
- )
+ self._check_bar_alignment(df, **kwargs)
@pytest.mark.slow
def test_bar_log_no_subplots(self):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Parametrize some tests in ``pandas/tests/plotting/test_frame.py``. | https://api.github.com/repos/pandas-dev/pandas/pulls/37735 | 2020-11-10T06:05:22Z | 2020-11-10T23:40:31Z | 2020-11-10T23:40:31Z | 2020-11-26T03:57:10Z |
TST: use default_axes=True where multiple plots | diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py
index 11a46858ba281..9bbb9743f1f0e 100644
--- a/pandas/tests/plotting/test_frame.py
+++ b/pandas/tests/plotting/test_frame.py
@@ -53,17 +53,25 @@ def test_plot(self):
df = self.tdf
_check_plot_works(df.plot, grid=False)
- # _check_plot_works adds an ax so catch warning. see GH #13188
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot, subplots=True)
+
+ # _check_plot_works adds an ax so use default_axes=True to avoid warning
+ axes = _check_plot_works(df.plot, default_axes=True, subplots=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot, subplots=True, layout=(-1, 2))
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ subplots=True,
+ layout=(-1, 2),
+ )
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot, subplots=True, use_index=False)
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ subplots=True,
+ use_index=False,
+ )
self._check_ticks_props(axes, xrot=0)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
@@ -84,8 +92,7 @@ def test_plot(self):
_check_plot_works(df.plot, xticks=[1, 5, 10])
_check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
- with tm.assert_produces_warning(UserWarning):
- _check_plot_works(df.plot, subplots=True, title="blah")
+ _check_plot_works(df.plot, default_axes=True, subplots=True, title="blah")
# We have to redo it here because _check_plot_works does two plots,
# once without an ax kwarg and once with an ax kwarg and the new sharex
@@ -1405,9 +1412,7 @@ def test_plot_bar(self):
_check_plot_works(df.plot.bar)
_check_plot_works(df.plot.bar, legend=False)
- # _check_plot_works adds an ax so catch warning. see GH #13188
- with tm.assert_produces_warning(UserWarning):
- _check_plot_works(df.plot.bar, subplots=True)
+ _check_plot_works(df.plot.bar, default_axes=True, subplots=True)
_check_plot_works(df.plot.bar, stacked=True)
df = DataFrame(
@@ -1629,9 +1634,13 @@ def test_boxplot_vertical(self):
self._check_text_labels(ax.get_yticklabels(), labels)
assert len(ax.lines) == self.bp_n_objects * len(numeric_cols)
- # _check_plot_works adds an ax so catch warning. see GH #13188
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot.box, subplots=True, vert=False, logx=True)
+ axes = _check_plot_works(
+ df.plot.box,
+ default_axes=True,
+ subplots=True,
+ vert=False,
+ logx=True,
+ )
self._check_axes_shape(axes, axes_num=3, layout=(1, 3))
self._check_ax_scales(axes, xaxis="log")
for ax, label in zip(axes, labels):
@@ -1698,8 +1707,12 @@ def test_kde_df(self):
ax = df.plot(kind="kde", rot=20, fontsize=5)
self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5)
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot, kind="kde", subplots=True)
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ kind="kde",
+ subplots=True,
+ )
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
axes = df.plot(kind="kde", logy=True, subplots=True)
@@ -1723,8 +1736,12 @@ def test_hist_df(self):
expected = [pprint_thing(c) for c in df.columns]
self._check_legend_labels(ax, labels=expected)
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot.hist, subplots=True, logy=True)
+ axes = _check_plot_works(
+ df.plot.hist,
+ default_axes=True,
+ subplots=True,
+ logy=True,
+ )
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
self._check_ax_scales(axes, yaxis="log")
@@ -2624,9 +2641,11 @@ def test_pie_df(self):
ax = _check_plot_works(df.plot.pie, y=2)
self._check_text_labels(ax.texts, df.index)
- # _check_plot_works adds an ax so catch warning. see GH #13188
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(df.plot.pie, subplots=True)
+ axes = _check_plot_works(
+ df.plot.pie,
+ default_axes=True,
+ subplots=True,
+ )
assert len(axes) == len(df.columns)
for ax in axes:
self._check_text_labels(ax.texts, df.index)
@@ -2635,10 +2654,13 @@ def test_pie_df(self):
labels = ["A", "B", "C", "D", "E"]
color_args = ["r", "g", "b", "c", "m"]
- with tm.assert_produces_warning(UserWarning):
- axes = _check_plot_works(
- df.plot.pie, subplots=True, labels=labels, colors=color_args
- )
+ axes = _check_plot_works(
+ df.plot.pie,
+ default_axes=True,
+ subplots=True,
+ labels=labels,
+ colors=color_args,
+ )
assert len(axes) == len(df.columns)
for ax in axes:
@@ -2745,16 +2767,15 @@ def test_errorbar_plot_different_kinds(self, kind):
ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind)
self._check_has_errorbars(ax, xerr=2, yerr=2)
- msg = (
- "To output multiple subplots, "
- "the figure containing the passed axes is being cleared"
+ axes = _check_plot_works(
+ df.plot,
+ default_axes=True,
+ yerr=df_err,
+ xerr=df_err,
+ subplots=True,
+ kind=kind,
)
- with tm.assert_produces_warning(UserWarning, match=msg):
- # Similar warnings were observed in GH #13188
- axes = _check_plot_works(
- df.plot, yerr=df_err, xerr=df_err, subplots=True, kind=kind
- )
- self._check_has_errorbars(axes, xerr=1, yerr=1)
+ self._check_has_errorbars(axes, xerr=1, yerr=1)
@pytest.mark.xfail(reason="Iterator is consumed", raises=ValueError)
@pytest.mark.slow
@@ -2826,14 +2847,14 @@ def test_errorbar_timeseries(self, kind):
ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
self._check_has_errorbars(ax, xerr=0, yerr=2)
- msg = (
- "To output multiple subplots, "
- "the figure containing the passed axes is being cleared"
+ axes = _check_plot_works(
+ tdf.plot,
+ default_axes=True,
+ kind=kind,
+ yerr=tdf_err,
+ subplots=True,
)
- with tm.assert_produces_warning(UserWarning, match=msg):
- # Similar warnings were observed in GH #13188
- axes = _check_plot_works(tdf.plot, kind=kind, yerr=tdf_err, subplots=True)
- self._check_has_errorbars(axes, xerr=0, yerr=1)
+ self._check_has_errorbars(axes, xerr=0, yerr=1)
def test_errorbar_asymmetrical(self):
np.random.seed(0)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Use new kwarg ``default_axes`` in ``_check_plot_works`` (#37274), which allows one to eliminate catching warnings related to multiple subplots created.
There warnings are not related to the plotting function, but rather were caused by the ``_check_plot_works`` itself.
| https://api.github.com/repos/pandas-dev/pandas/pulls/37734 | 2020-11-10T06:00:23Z | 2020-11-10T22:56:31Z | 2020-11-10T22:56:31Z | 2020-11-10T22:56:37Z |
API: consistently raise TypeError for invalid-typed fill_value | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index f751a91cecf19..49f617501980b 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -322,6 +322,10 @@ Other API changes
^^^^^^^^^^^^^^^^^
- Sorting in descending order is now stable for :meth:`Series.sort_values` and :meth:`Index.sort_values` for DateTime-like :class:`Index` subclasses. This will affect sort order when sorting :class:`DataFrame` on multiple columns, sorting with a key function that produces duplicates, or requesting the sorting index when using :meth:`Index.sort_values`. When using :meth:`Series.value_counts`, count of missing values is no longer the last in the list of duplicate counts, and its position corresponds to the position in the original :class:`Series`. When using :meth:`Index.sort_values` for DateTime-like :class:`Index` subclasses, NaTs ignored the ``na_position`` argument and were sorted to the beggining. Now they respect ``na_position``, the default being ``last``, same as other :class:`Index` subclasses. (:issue:`35992`)
+- Passing an invalid ``fill_value`` to :meth:`Categorical.take`, :meth:`DatetimeArray.take`, :meth:`TimedeltaArray.take`, :meth:`PeriodArray.take` now raises ``TypeError`` instead of ``ValueError`` (:issue:`37733`)
+- Passing an invalid ``fill_value`` to :meth:`Series.shift` with a ``CategoricalDtype`` now raises ``TypeError`` instead of ``ValueError`` (:issue:`37733`)
+- Passing an invalid value to :meth:`IntervalIndex.insert` or :meth:`CategoricalIndex.insert` now raises a ``TypeError`` instead of a ``ValueError`` (:issue:`37733`)
+- Attempting to reindex a :class:`Series` with a :class:`CategoricalIndex` with an invalid ``fill_value`` now raises ``TypeError`` instead of ``ValueError`` (:issue:`37733`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index d84e2e2ad295b..ddcf225d3585f 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -74,7 +74,7 @@ def take(
def _validate_fill_value(self, fill_value):
"""
If a fill_value is passed to `take` convert it to a representation
- suitable for self._ndarray, raising ValueError if this is not possible.
+ suitable for self._ndarray, raising TypeError if this is not possible.
Parameters
----------
@@ -86,7 +86,7 @@ def _validate_fill_value(self, fill_value):
Raises
------
- ValueError
+ TypeError
"""
raise AbstractMethodError(self)
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 9f011bc9d2651..970163df908ec 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1190,7 +1190,7 @@ def _validate_searchsorted_value(self, value):
def _validate_fill_value(self, fill_value):
"""
Convert a user-facing fill_value to a representation to use with our
- underlying ndarray, raising ValueError if this is not possible.
+ underlying ndarray, raising TypeError if this is not possible.
Parameters
----------
@@ -1202,7 +1202,7 @@ def _validate_fill_value(self, fill_value):
Raises
------
- ValueError
+ TypeError
"""
if is_valid_nat_for_dtype(fill_value, self.categories.dtype):
@@ -1210,7 +1210,7 @@ def _validate_fill_value(self, fill_value):
elif fill_value in self.categories:
fill_value = self._unbox_scalar(fill_value)
else:
- raise ValueError(
+ raise TypeError(
f"'fill_value={fill_value}' is not present "
"in this Categorical's categories"
)
@@ -1659,7 +1659,6 @@ def fillna(self, value=None, method=None, limit=None):
# We get ndarray or Categorical if called via Series.fillna,
# where it will unwrap another aligned Series before getting here
codes[mask] = new_codes[mask]
-
else:
codes[mask] = new_codes
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index f2f843886e802..d81a4567732bc 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -462,7 +462,7 @@ def _validate_comparison_value(self, other):
def _validate_fill_value(self, fill_value):
"""
If a fill_value is passed to `take` convert it to an i8 representation,
- raising ValueError if this is not possible.
+ raising TypeError if this is not possible.
Parameters
----------
@@ -474,19 +474,9 @@ def _validate_fill_value(self, fill_value):
Raises
------
- ValueError
+ TypeError
"""
- msg = (
- f"'fill_value' should be a {self._scalar_type}. "
- f"Got '{str(fill_value)}'."
- )
- try:
- return self._validate_scalar(fill_value)
- except TypeError as err:
- if "Cannot compare tz-naive and tz-aware" in str(err):
- # tzawareness-compat
- raise
- raise ValueError(msg) from err
+ return self._validate_scalar(fill_value)
def _validate_shift_value(self, fill_value):
# TODO(2.0): once this deprecation is enforced, use _validate_fill_value
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index a2eb506c6747a..977e4abff4287 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -649,7 +649,7 @@ def fillna(self, value=None, method=None, limit=None):
if limit is not None:
raise TypeError("limit is not supported for IntervalArray.")
- value_left, value_right = self._validate_fillna_value(value)
+ value_left, value_right = self._validate_fill_value(value)
left = self.left.fillna(value=value_left)
right = self.right.fillna(value=value_right)
@@ -870,7 +870,7 @@ def _validate_scalar(self, value):
# GH#18295
left = right = value
else:
- raise ValueError(
+ raise TypeError(
"can only insert Interval objects and NA into an IntervalArray"
)
return left, right
@@ -878,17 +878,6 @@ def _validate_scalar(self, value):
def _validate_fill_value(self, value):
return self._validate_scalar(value)
- def _validate_fillna_value(self, value):
- # This mirrors Datetimelike._validate_fill_value
- try:
- return self._validate_scalar(value)
- except ValueError as err:
- msg = (
- "'IntervalArray.fillna' only supports filling with a "
- f"scalar 'pandas.Interval'. Got a '{type(value).__name__}' instead."
- )
- raise TypeError(msg) from err
-
def _validate_setitem_value(self, value):
needs_float_conversion = False
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 5a3f2b0853c4f..5790c6db6405f 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3660,7 +3660,12 @@ def insert(self, loc: int, item):
# must insert at end otherwise you have to recompute all the
# other codes
lev_loc = len(level)
- level = level.insert(lev_loc, k)
+ try:
+ level = level.insert(lev_loc, k)
+ except TypeError:
+ # TODO: Should this be done inside insert?
+ # TODO: smarter casting rules?
+ level = level.astype(object).insert(lev_loc, k)
else:
lev_loc = level.get_loc(k)
diff --git a/pandas/tests/arrays/categorical/test_take.py b/pandas/tests/arrays/categorical/test_take.py
index 7a27f5c3e73ad..97d9db483c401 100644
--- a/pandas/tests/arrays/categorical/test_take.py
+++ b/pandas/tests/arrays/categorical/test_take.py
@@ -79,7 +79,7 @@ def test_take_fill_value_new_raises(self):
# https://github.com/pandas-dev/pandas/issues/23296
cat = Categorical(["a", "b", "c"])
xpr = r"'fill_value=d' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=xpr):
+ with pytest.raises(TypeError, match=xpr):
cat.take([0, 1, -1], fill_value="d", allow_fill=True)
def test_take_nd_deprecated(self):
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index ec20c829f1544..c24f789b30313 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -145,8 +145,8 @@ def test_take_fill_raises(self, fill_value):
arr = self.array_cls._simple_new(data, freq="D")
- msg = f"'fill_value' should be a {self.dtype}. Got '{fill_value}'"
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
arr.take([0, 1], allow_fill=True, fill_value=fill_value)
def test_take_fill(self):
@@ -169,8 +169,8 @@ def test_take_fill_str(self, arr1d):
expected = arr1d[[-1, 1]]
tm.assert_equal(result, expected)
- msg = r"'fill_value' should be a <.*>\. Got 'foo'"
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
arr1d.take([-1, 1], allow_fill=True, fill_value="foo")
def test_concat_same_type(self):
@@ -745,13 +745,12 @@ def test_take_fill_valid(self, arr1d):
result = arr.take([-1, 1], allow_fill=True, fill_value=now)
assert result[0] == now
- msg = f"'fill_value' should be a {self.dtype}. Got '0 days 00:00:00'."
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
# fill_value Timedelta invalid
arr.take([-1, 1], allow_fill=True, fill_value=now - now)
- msg = f"'fill_value' should be a {self.dtype}. Got '2014Q1'."
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
arr.take([-1, 1], allow_fill=True, fill_value=pd.Period("2014Q1"))
@@ -763,14 +762,13 @@ def test_take_fill_valid(self, arr1d):
arr.take([-1, 1], allow_fill=True, fill_value=now)
value = pd.NaT.value
- msg = f"'fill_value' should be a {self.dtype}. Got '{value}'."
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
# require NaT, not iNaT, as it could be confused with an integer
arr.take([-1, 1], allow_fill=True, fill_value=value)
value = np.timedelta64("NaT", "ns")
- msg = f"'fill_value' should be a {self.dtype}. Got '{str(value)}'."
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
# require appropriate-dtype if we have a NA value
arr.take([-1, 1], allow_fill=True, fill_value=value)
@@ -932,20 +930,18 @@ def test_take_fill_valid(self, timedelta_index):
now = pd.Timestamp.now()
value = now
- msg = f"'fill_value' should be a {self.dtype}. Got '{value}'."
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
# fill_value Timestamp invalid
arr.take([0, 1], allow_fill=True, fill_value=value)
value = now.to_period("D")
- msg = f"'fill_value' should be a {self.dtype}. Got '{value}'."
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
arr.take([0, 1], allow_fill=True, fill_value=value)
value = np.datetime64("NaT", "ns")
- msg = f"'fill_value' should be a {self.dtype}. Got '{str(value)}'."
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
# require appropriate-dtype if we have a NA value
arr.take([-1, 1], allow_fill=True, fill_value=value)
@@ -981,14 +977,13 @@ def test_take_fill_valid(self, arr1d):
arr = arr1d
value = pd.NaT.value
- msg = f"'fill_value' should be a {self.dtype}. Got '{value}'."
- with pytest.raises(ValueError, match=msg):
+ msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
+ with pytest.raises(TypeError, match=msg):
# require NaT, not iNaT, as it could be confused with an integer
arr.take([-1, 1], allow_fill=True, fill_value=value)
value = np.timedelta64("NaT", "ns")
- msg = f"'fill_value' should be a {self.dtype}. Got '{str(value)}'."
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
# require appropriate-dtype if we have a NA value
arr.take([-1, 1], allow_fill=True, fill_value=value)
diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py
index 0d81e8e733842..f96a15d5b2e7c 100644
--- a/pandas/tests/arrays/test_period.py
+++ b/pandas/tests/arrays/test_period.py
@@ -113,7 +113,8 @@ def test_take_raises():
with pytest.raises(IncompatibleFrequency, match="freq"):
arr.take([0, -1], allow_fill=True, fill_value=pd.Period("2000", freq="W"))
- with pytest.raises(ValueError, match="foo"):
+ msg = "value should be a 'Period' or 'NaT'. Got 'str' instead"
+ with pytest.raises(TypeError, match=msg):
arr.take([0, -1], allow_fill=True, fill_value="foo")
diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py
index 4fdcf930d224f..ec834118ea7a1 100644
--- a/pandas/tests/extension/test_interval.py
+++ b/pandas/tests/extension/test_interval.py
@@ -136,8 +136,8 @@ def test_fillna_limit_backfill(self):
def test_fillna_series(self):
pass
- def test_non_scalar_raises(self, data_missing):
- msg = "Got a 'list' instead."
+ def test_fillna_non_scalar_raises(self, data_missing):
+ msg = "can only insert Interval objects and NA into an IntervalArray"
with pytest.raises(TypeError, match=msg):
data_missing.fillna([1, 1])
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index d1425c85caaee..3fa17c1764de3 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -245,7 +245,7 @@ def test_unstack_fill_frame_categorical(self):
# Fill with non-category results in a ValueError
msg = r"'fill_value=d' is not present in"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
data.unstack(fill_value="d")
# Fill with category value replaces missing values as expected
diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py
index 324a2535bc465..1a05dbe2bb230 100644
--- a/pandas/tests/indexes/categorical/test_category.py
+++ b/pandas/tests/indexes/categorical/test_category.py
@@ -172,7 +172,7 @@ def test_insert(self):
# invalid
msg = "'fill_value=d' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
ci.insert(0, "d")
# GH 18295 (test missing)
@@ -184,7 +184,7 @@ def test_insert(self):
def test_insert_na_mismatched_dtype(self):
ci = CategoricalIndex([0, 1, 1])
msg = "'fill_value=NaT' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
ci.insert(0, pd.NaT)
def test_delete(self):
diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py
index 189582ea635d2..668c559abd08e 100644
--- a/pandas/tests/indexes/categorical/test_reindex.py
+++ b/pandas/tests/indexes/categorical/test_reindex.py
@@ -57,5 +57,5 @@ def test_reindex_missing_category(self):
# GH: 18185
ser = Series([1, 2, 3, 1], dtype="category")
msg = "'fill_value=-1' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
ser.reindex([1, 2, 3, 4, 5], fill_value=-1)
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 157446b1fff5d..45683ba48b4c4 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -192,7 +192,7 @@ def test_insert(self, data):
# invalid type
msg = "can only insert Interval objects and NA into an IntervalArray"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
data.insert(1, "foo")
# invalid closed
@@ -213,7 +213,7 @@ def test_insert(self, data):
if data.left.dtype.kind not in ["m", "M"]:
# trying to insert pd.NaT into a numeric-dtyped Index should cast/raise
msg = "can only insert Interval objects and NA into an IntervalArray"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
result = data.insert(1, pd.NaT)
else:
result = data.insert(1, pd.NaT)
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index 20d7662855ab3..79e9df8ce30cb 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -60,9 +60,9 @@ def test_loc_scalar(self):
df.loc["d"] = 10
msg = "'fill_value=d' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
df.loc["d", "A"] = 10
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
df.loc["d", "C"] = 10
with pytest.raises(KeyError, match="^1$"):
diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py
index d38d70abba923..60ec0a90e906f 100644
--- a/pandas/tests/series/methods/test_shift.py
+++ b/pandas/tests/series/methods/test_shift.py
@@ -170,7 +170,7 @@ def test_shift_categorical_fill_value(self):
# check for incorrect fill_value
msg = "'fill_value=f' is not present in this Categorical's categories"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
ts.shift(1, fill_value="f")
def test_shift_dst(self):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This makes us consistent about raising TypeError when passing a wrong-typed fill_value to e.g. `take`. The downside is that we changed `Categorical.take` from TypeError to ValueError back in 1.1.0 #33660, so theres a bit of whiplash.
The upside (besides this just being More Correct) is that we will be just about fully sharing setitem-like validator methods. | https://api.github.com/repos/pandas-dev/pandas/pulls/37733 | 2020-11-10T04:18:21Z | 2020-11-13T05:09:37Z | 2020-11-13T05:09:37Z | 2020-11-14T04:22:12Z |
CI/DOC: unpin gitdb #35823 | diff --git a/environment.yml b/environment.yml
index 806119631d5ee..c9b1fa108c00b 100644
--- a/environment.yml
+++ b/environment.yml
@@ -26,7 +26,7 @@ dependencies:
# documentation
- gitpython # obtain contributors from git for whatsnew
- - gitdb2=2.0.6 # GH-32060
+ - gitdb
- sphinx
# documentation (jupyter notebooks)
diff --git a/requirements-dev.txt b/requirements-dev.txt
index deaed8ab9d5f1..d5510ddc24034 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -15,7 +15,7 @@ isort>=5.2.1
mypy==0.730
pycodestyle
gitpython
-gitdb2==2.0.6
+gitdb
sphinx
nbconvert>=5.4.1
nbsphinx
| - [x] closes #35823
| https://api.github.com/repos/pandas-dev/pandas/pulls/35824 | 2020-08-20T15:35:04Z | 2020-08-21T21:12:59Z | 2020-08-21T21:12:59Z | 2020-08-21T21:52:46Z |
Backport PR #35801 on branch 1.1.x (DOC: another pass of v1.1.1 release notes) | diff --git a/doc/source/whatsnew/v1.1.1.rst b/doc/source/whatsnew/v1.1.1.rst
index 43ffed273adbc..721f07c865409 100644
--- a/doc/source/whatsnew/v1.1.1.rst
+++ b/doc/source/whatsnew/v1.1.1.rst
@@ -1,6 +1,6 @@
.. _whatsnew_111:
-What's new in 1.1.1 (August XX, 2020)
+What's new in 1.1.1 (August 20, 2020)
-------------------------------------
These are the changes in pandas 1.1.1. See :ref:`release` for a full changelog
@@ -27,7 +27,7 @@ Fixed regressions
- Fixed regression in ``.groupby(..).rolling(..)`` where a segfault would occur with ``center=True`` and an odd number of values (:issue:`35552`)
- Fixed regression in :meth:`DataFrame.apply` where functions that altered the input in-place only operated on a single row (:issue:`35462`)
- Fixed regression in :meth:`DataFrame.reset_index` would raise a ``ValueError`` on empty :class:`DataFrame` with a :class:`MultiIndex` with a ``datetime64`` dtype level (:issue:`35606`, :issue:`35657`)
-- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
+- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index``, ``right_index`` and ``tolerance`` were set (:issue:`35558`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a custom ``BaseIndexer`` would be ignored (:issue:`35557`)
- Fixed regression in :meth:`DataFrame.replace` and :meth:`Series.replace` where compiled regular expressions would be ignored during replacement (:issue:`35680`)
- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` where a list of functions would produce the wrong results if at least one of the functions did not aggregate (:issue:`35490`)
@@ -40,11 +40,11 @@ Fixed regressions
Bug fixes
~~~~~~~~~
-- Bug in :class:`~pandas.io.formats.style.Styler` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
+- Bug in :class:`~pandas.io.formats.style.Styler` whereby ``cell_ids`` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`)
-- Bug in :meth:`to_timedelta` fails when arg is a :class:`Series` with `Int64` dtype containing null values (:issue:`35574`)
+- Bug in :meth:`to_timedelta` fails when ``arg`` is a :class:`Series` with ``Int64`` dtype containing null values (:issue:`35574`)
- Bug in ``.groupby(..).rolling(..)`` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
-- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when data and index have mismatched lengths (:issue:`33437`)
+- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when ``data`` and ``index`` have mismatched lengths (:issue:`33437`)
.. ---------------------------------------------------------------------------
| Backport PR #35801: DOC: another pass of v1.1.1 release notes | https://api.github.com/repos/pandas-dev/pandas/pulls/35822 | 2020-08-20T15:06:03Z | 2020-08-20T16:36:03Z | 2020-08-20T16:36:02Z | 2020-08-20T16:36:03Z |
Backport PR #35809 on branch 1.1.x (CI: more xfail failing 32-bit tests) | diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py
index a9590c7e1233a..d0a62374d0888 100644
--- a/pandas/tests/window/test_grouper.py
+++ b/pandas/tests/window/test_grouper.py
@@ -215,6 +215,7 @@ def foo(x):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_center_center(self):
# GH 35552
series = Series(range(1, 6))
@@ -280,6 +281,7 @@ def test_groupby_rolling_center_center(self):
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_subselect_rolling(self):
# GH 35486
df = DataFrame(
@@ -305,6 +307,7 @@ def test_groupby_subselect_rolling(self):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_custom_indexer(self):
# GH 35557
class SimpleIndexer(pd.api.indexers.BaseIndexer):
@@ -328,6 +331,7 @@ def get_window_bounds(
expected = df.groupby(df.index).rolling(window=3, min_periods=1).sum()
tm.assert_frame_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_subset_with_closed(self):
# GH 35549
df = pd.DataFrame(
@@ -352,6 +356,7 @@ def test_groupby_rolling_subset_with_closed(self):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_subset_rolling_subset_with_closed(self):
# GH 35549
df = pd.DataFrame(
| Backport PR #35809: CI: more xfail failing 32-bit tests | https://api.github.com/repos/pandas-dev/pandas/pulls/35821 | 2020-08-20T12:05:33Z | 2020-08-20T13:32:05Z | 2020-08-20T13:32:05Z | 2020-08-20T13:32:05Z |
CI/DOC: unpin sphinx, fix autodoc usage | diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst
index e3dfb552651a0..4d9d18e3d204e 100644
--- a/doc/source/reference/frame.rst
+++ b/doc/source/reference/frame.rst
@@ -343,6 +343,7 @@ Sparse-dtype specific methods and attributes are provided under the
.. autosummary::
:toctree: api/
+ :template: autosummary/accessor_method.rst
DataFrame.sparse.from_spmatrix
DataFrame.sparse.to_coo
diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index 3b595ba5ab206..ae3e121ca8212 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -522,6 +522,7 @@ Sparse-dtype specific methods and attributes are provided under the
.. autosummary::
:toctree: api/
+ :template: autosummary/accessor_method.rst
Series.sparse.from_coo
Series.sparse.to_coo
diff --git a/environment.yml b/environment.yml
index aaabf09b8f190..806119631d5ee 100644
--- a/environment.yml
+++ b/environment.yml
@@ -27,7 +27,7 @@ dependencies:
# documentation
- gitpython # obtain contributors from git for whatsnew
- gitdb2=2.0.6 # GH-32060
- - sphinx<=3.1.1
+ - sphinx
# documentation (jupyter notebooks)
- nbconvert>=5.4.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 3d0778b74ccbd..deaed8ab9d5f1 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -16,7 +16,7 @@ mypy==0.730
pycodestyle
gitpython
gitdb2==2.0.6
-sphinx<=3.1.1
+sphinx
nbconvert>=5.4.1
nbsphinx
pandoc
| - [x] closes #35138
| https://api.github.com/repos/pandas-dev/pandas/pulls/35815 | 2020-08-20T02:14:50Z | 2020-08-20T07:24:26Z | 2020-08-20T07:24:26Z | 2020-08-21T16:06:02Z |
TST: Fix test_parquet failures for pyarrow 1.0 | diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 3a3ba99484a3a..4e0c16c71a6a8 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -565,15 +565,22 @@ def test_s3_roundtrip(self, df_compat, s3_resource, pa):
@pytest.mark.parametrize("partition_col", [["A"], []])
def test_s3_roundtrip_for_dir(self, df_compat, s3_resource, pa, partition_col):
# GH #26388
- # https://github.com/apache/arrow/blob/master/python/pyarrow/tests/test_parquet.py#L2716
- # As per pyarrow partitioned columns become 'categorical' dtypes
- # and are added to back of dataframe on read
- if partition_col and pd.compat.is_platform_windows():
- pytest.skip("pyarrow/win incompatibility #35791")
-
expected_df = df_compat.copy()
- if partition_col:
- expected_df[partition_col] = expected_df[partition_col].astype("category")
+
+ # GH #35791
+ # read_table uses the new Arrow Datasets API since pyarrow 1.0.0
+ # Previous behaviour was pyarrow partitioned columns become 'category' dtypes
+ # These are added to back of dataframe on read. In new API category dtype is
+ # only used if partition field is string.
+ legacy_read_table = LooseVersion(pyarrow.__version__) < LooseVersion("1.0.0")
+ if partition_col and legacy_read_table:
+ partition_col_type = "category"
+ else:
+ partition_col_type = "int32"
+
+ expected_df[partition_col] = expected_df[partition_col].astype(
+ partition_col_type
+ )
check_round_trip(
df_compat,
| - [x] closes https://github.com/pandas-dev/pandas/issues/35791
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
cc @martindurant -> looks like this is a pyarrow 1.0.0 compat issue (read_table uses the new API) - https://arrow.apache.org/docs/python/generated/pyarrow.parquet.read_table.html
I noticed the partition cols are casted from int64 -> int32 is that expected pyarrow behaviour? From the write_table docs looking at version 1.0/2.0 it suggests it is https://arrow.apache.org/docs/python/generated/pyarrow.parquet.write_table.html#pyarrow.parquet.write_table
| https://api.github.com/repos/pandas-dev/pandas/pulls/35814 | 2020-08-20T01:31:11Z | 2020-08-25T06:41:49Z | 2020-08-25T06:41:49Z | 2020-08-25T07:08:14Z |
WEB: Add new Maintainers to Team Page | diff --git a/web/pandas/config.yml b/web/pandas/config.yml
index 23575cc123050..9a178d26659c3 100644
--- a/web/pandas/config.yml
+++ b/web/pandas/config.yml
@@ -79,6 +79,13 @@ maintainers:
- datapythonista
- simonjayhawkins
- topper-123
+ - alimcmaster1
+ - bashtage
+ - charlesdong1991
+ - Dr-Irv
+ - dsaxton
+ - MarcoGorelli
+ - rhshadrach
emeritus:
- Wouter Overmeire
- Skipper Seabold
| Add new maintainers.
cc:
@bashtage
@charlesdong1991
@Dr-Irv
@dsaxton
@MarcoGorelli
@rhshadrach
In case anyone doesn't want to appear here: https://pandas.pydata.org/about/team.html | https://api.github.com/repos/pandas-dev/pandas/pulls/35812 | 2020-08-19T22:37:48Z | 2020-08-20T16:26:31Z | 2020-08-20T16:26:31Z | 2020-08-20T16:26:36Z |
CI: more xfail failing 32-bit tests | diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py
index a9590c7e1233a..d0a62374d0888 100644
--- a/pandas/tests/window/test_grouper.py
+++ b/pandas/tests/window/test_grouper.py
@@ -215,6 +215,7 @@ def foo(x):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_center_center(self):
# GH 35552
series = Series(range(1, 6))
@@ -280,6 +281,7 @@ def test_groupby_rolling_center_center(self):
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_subselect_rolling(self):
# GH 35486
df = DataFrame(
@@ -305,6 +307,7 @@ def test_groupby_subselect_rolling(self):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_custom_indexer(self):
# GH 35557
class SimpleIndexer(pd.api.indexers.BaseIndexer):
@@ -328,6 +331,7 @@ def get_window_bounds(
expected = df.groupby(df.index).rolling(window=3, min_periods=1).sum()
tm.assert_frame_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_rolling_subset_with_closed(self):
# GH 35549
df = pd.DataFrame(
@@ -352,6 +356,7 @@ def test_groupby_rolling_subset_with_closed(self):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.xfail(not compat.IS64, reason="GH-35294")
def test_groupby_subset_rolling_subset_with_closed(self):
# GH 35549
df = pd.DataFrame(
| xref #35294 and https://github.com/pandas-dev/pandas/issues/35489#issuecomment-676550757 | https://api.github.com/repos/pandas-dev/pandas/pulls/35809 | 2020-08-19T18:03:26Z | 2020-08-20T12:03:31Z | 2020-08-20T12:03:31Z | 2020-08-20T12:05:50Z |
Backport PR #35672 on branch 1.1.x CI: test_chunks_have_consistent_numerical_type periodically fails on 1.1.x | diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index 12e73bae40eac..bacce7585c205 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -1138,6 +1138,7 @@ def test_parse_integers_above_fp_precision(all_parsers):
tm.assert_frame_equal(result, expected)
+@pytest.mark.xfail(reason="ResourceWarning #35660", strict=False)
def test_chunks_have_consistent_numerical_type(all_parsers):
parser = all_parsers
integers = [str(i) for i in range(499999)]
@@ -1151,6 +1152,7 @@ def test_chunks_have_consistent_numerical_type(all_parsers):
assert result.a.dtype == float
+@pytest.mark.xfail(reason="ResourceWarning #35660", strict=False)
def test_warn_if_chunks_have_mismatched_type(all_parsers):
warning_type = None
parser = all_parsers
| PR directly against 1.1.x
effectively backport of #35672 | https://api.github.com/repos/pandas-dev/pandas/pulls/35808 | 2020-08-19T17:37:14Z | 2020-08-20T13:41:49Z | 2020-08-20T13:41:49Z | 2020-08-20T13:41:55Z |
Backport PR #35776 on branch 1.1.x (Changed 'int' type to 'integer' in to_numeric docstring) | diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index d8db196e4b92f..1531f7b292365 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -234,7 +234,7 @@ class SparseArray(PandasObject, ExtensionArray, ExtensionOpsMixin):
3. ``data.dtype.fill_value`` if `fill_value` is None and `dtype`
is not a ``SparseDtype`` and `data` is a ``SparseArray``.
- kind : {'int', 'block'}, default 'int'
+ kind : {'integer', 'block'}, default 'integer'
The type of storage for sparse locations.
* 'block': Stores a `block` and `block_length` for each
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index 41548931f17f8..cff4695603d06 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -40,13 +40,13 @@ def to_numeric(arg, errors="raise", downcast=None):
- If 'raise', then invalid parsing will raise an exception.
- If 'coerce', then invalid parsing will be set as NaN.
- If 'ignore', then invalid parsing will return the input.
- downcast : {'int', 'signed', 'unsigned', 'float'}, default None
+ downcast : {'integer', 'signed', 'unsigned', 'float'}, default None
If not None, and if the data has been successfully cast to a
numerical dtype (or if the data was numeric to begin with),
downcast that resulting data to the smallest numerical dtype
possible according to the following rules:
- - 'int' or 'signed': smallest signed int dtype (min.: np.int8)
+ - 'integer' or 'signed': smallest signed int dtype (min.: np.int8)
- 'unsigned': smallest unsigned int dtype (min.: np.uint8)
- 'float': smallest float dtype (min.: np.float32)
| Backport PR #35776: Changed 'int' type to 'integer' in to_numeric docstring | https://api.github.com/repos/pandas-dev/pandas/pulls/35806 | 2020-08-19T13:16:52Z | 2020-08-19T14:25:28Z | 2020-08-19T14:25:28Z | 2020-08-19T14:25:28Z |
DOC: another pass of v1.1.1 release notes | diff --git a/doc/source/whatsnew/v1.1.1.rst b/doc/source/whatsnew/v1.1.1.rst
index 43ffed273adbc..721f07c865409 100644
--- a/doc/source/whatsnew/v1.1.1.rst
+++ b/doc/source/whatsnew/v1.1.1.rst
@@ -1,6 +1,6 @@
.. _whatsnew_111:
-What's new in 1.1.1 (August XX, 2020)
+What's new in 1.1.1 (August 20, 2020)
-------------------------------------
These are the changes in pandas 1.1.1. See :ref:`release` for a full changelog
@@ -27,7 +27,7 @@ Fixed regressions
- Fixed regression in ``.groupby(..).rolling(..)`` where a segfault would occur with ``center=True`` and an odd number of values (:issue:`35552`)
- Fixed regression in :meth:`DataFrame.apply` where functions that altered the input in-place only operated on a single row (:issue:`35462`)
- Fixed regression in :meth:`DataFrame.reset_index` would raise a ``ValueError`` on empty :class:`DataFrame` with a :class:`MultiIndex` with a ``datetime64`` dtype level (:issue:`35606`, :issue:`35657`)
-- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
+- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index``, ``right_index`` and ``tolerance`` were set (:issue:`35558`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a custom ``BaseIndexer`` would be ignored (:issue:`35557`)
- Fixed regression in :meth:`DataFrame.replace` and :meth:`Series.replace` where compiled regular expressions would be ignored during replacement (:issue:`35680`)
- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` where a list of functions would produce the wrong results if at least one of the functions did not aggregate (:issue:`35490`)
@@ -40,11 +40,11 @@ Fixed regressions
Bug fixes
~~~~~~~~~
-- Bug in :class:`~pandas.io.formats.style.Styler` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
+- Bug in :class:`~pandas.io.formats.style.Styler` whereby ``cell_ids`` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`)
-- Bug in :meth:`to_timedelta` fails when arg is a :class:`Series` with `Int64` dtype containing null values (:issue:`35574`)
+- Bug in :meth:`to_timedelta` fails when ``arg`` is a :class:`Series` with ``Int64`` dtype containing null values (:issue:`35574`)
- Bug in ``.groupby(..).rolling(..)`` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
-- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when data and index have mismatched lengths (:issue:`33437`)
+- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when ``data`` and ``index`` have mismatched lengths (:issue:`33437`)
.. ---------------------------------------------------------------------------
| https://pandas.pydata.org/docs/dev/whatsnew/v1.1.1.html | https://api.github.com/repos/pandas-dev/pandas/pulls/35801 | 2020-08-19T12:27:32Z | 2020-08-20T15:05:47Z | 2020-08-20T15:05:47Z | 2020-08-20T15:07:07Z |
Backport PR #35787 on branch 1.1.x (DOC: clean v1.1.1 release notes) | diff --git a/doc/source/whatsnew/v1.1.1.rst b/doc/source/whatsnew/v1.1.1.rst
index ff5bbccf63ffe..43ffed273adbc 100644
--- a/doc/source/whatsnew/v1.1.1.rst
+++ b/doc/source/whatsnew/v1.1.1.rst
@@ -1,7 +1,7 @@
.. _whatsnew_111:
-What's new in 1.1.1 (?)
------------------------
+What's new in 1.1.1 (August XX, 2020)
+-------------------------------------
These are the changes in pandas 1.1.1. See :ref:`release` for a full changelog
including other versions of pandas.
@@ -15,20 +15,23 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`CategoricalIndex.format` where, when stringified scalars had different lengths, the shorter string would be right-filled with spaces, so it had the same length as the longest string (:issue:`35439`)
+- Fixed regression in :meth:`Series.truncate` when trying to truncate a single-element series (:issue:`35544`)
- Fixed regression where :meth:`DataFrame.to_numpy` would raise a ``RuntimeError`` for mixed dtypes when converting to ``str`` (:issue:`35455`)
- Fixed regression where :func:`read_csv` would raise a ``ValueError`` when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`35493`)
- Fixed regression where :func:`pandas.testing.assert_series_equal` would raise an error when non-numeric dtypes were passed with ``check_exact=True`` (:issue:`35446`)
-- Fixed regression in :class:`pandas.core.groupby.RollingGroupby` where column selection was ignored (:issue:`35486`)
-- Fixed regression where :meth:`DataFrame.interpolate` would raise a ``TypeError`` when the :class:`DataFrame` was empty (:issue:`35598`).
+- Fixed regression in ``.groupby(..).rolling(..)`` where column selection was ignored (:issue:`35486`)
+- Fixed regression where :meth:`DataFrame.interpolate` would raise a ``TypeError`` when the :class:`DataFrame` was empty (:issue:`35598`)
- Fixed regression in :meth:`DataFrame.shift` with ``axis=1`` and heterogeneous dtypes (:issue:`35488`)
- Fixed regression in :meth:`DataFrame.diff` with read-only data (:issue:`35559`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a segfault would occur with ``center=True`` and an odd number of values (:issue:`35552`)
- Fixed regression in :meth:`DataFrame.apply` where functions that altered the input in-place only operated on a single row (:issue:`35462`)
- Fixed regression in :meth:`DataFrame.reset_index` would raise a ``ValueError`` on empty :class:`DataFrame` with a :class:`MultiIndex` with a ``datetime64`` dtype level (:issue:`35606`, :issue:`35657`)
-- Fixed regression where :meth:`DataFrame.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
+- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a custom ``BaseIndexer`` would be ignored (:issue:`35557`)
- Fixed regression in :meth:`DataFrame.replace` and :meth:`Series.replace` where compiled regular expressions would be ignored during replacement (:issue:`35680`)
-- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.agg` where a list of functions would produce the wrong results if at least one of the functions did not aggregate. (:issue:`35490`)
+- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` where a list of functions would produce the wrong results if at least one of the functions did not aggregate (:issue:`35490`)
+- Fixed memory usage issue when instantiating large :class:`pandas.arrays.StringArray` (:issue:`35499`)
.. ---------------------------------------------------------------------------
@@ -37,50 +40,11 @@ Fixed regressions
Bug fixes
~~~~~~~~~
-- Bug in ``Styler`` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`).
-- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`).
-
-Categorical
-^^^^^^^^^^^
-
-- Bug in :meth:`CategoricalIndex.format` where, when stringified scalars had different lengths, the shorter string would be right-filled with spaces, so it had the same length as the longest string (:issue:`35439`)
-
-
-**Datetimelike**
-
--
--
-
-**Timedelta**
-
+- Bug in :class:`~pandas.io.formats.style.Styler` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
+- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`)
- Bug in :meth:`to_timedelta` fails when arg is a :class:`Series` with `Int64` dtype containing null values (:issue:`35574`)
-
-
-**Numeric**
-
--
--
-
-**Groupby/resample/rolling**
-
-- Bug in :class:`pandas.core.groupby.RollingGroupby` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
-
-**Plotting**
-
--
-
-**Indexing**
-
-- Bug in :meth:`Series.truncate` when trying to truncate a single-element series (:issue:`35544`)
-
-**DataFrame**
+- Bug in ``.groupby(..).rolling(..)`` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when data and index have mismatched lengths (:issue:`33437`)
--
-
-**Strings**
-
-- fix memory usage issue when instantiating large :class:`pandas.arrays.StringArray` (:issue:`35499`)
-
.. ---------------------------------------------------------------------------
| Backport PR #35787: DOC: clean v1.1.1 release notes | https://api.github.com/repos/pandas-dev/pandas/pulls/35800 | 2020-08-19T09:49:44Z | 2020-08-19T11:34:40Z | 2020-08-19T11:34:40Z | 2020-08-19T11:34:40Z |
TST: resample does not yield empty groups (#10603) | diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index 0fbb60c176b30..3fa85e62d028c 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -150,3 +150,18 @@ def test_resample_timedelta_edge_case(start, end, freq, resample_freq):
tm.assert_index_equal(result.index, expected_index)
assert result.index.freq == expected_index.freq
assert not np.isnan(result[-1])
+
+
+def test_resample_with_timedelta_yields_no_empty_groups():
+ # GH 10603
+ df = pd.DataFrame(
+ np.random.normal(size=(10000, 4)),
+ index=pd.timedelta_range(start="0s", periods=10000, freq="3906250n"),
+ )
+ result = df.loc["1s":, :].resample("3s").apply(lambda x: len(x))
+
+ expected = pd.DataFrame(
+ [[768.0] * 4] * 12 + [[528.0] * 4],
+ index=pd.timedelta_range(start="1s", periods=13, freq="3s"),
+ )
+ tm.assert_frame_equal(result, expected)
| - [x] closes #10603
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This adds a test to verify that resample does not yield empty groups.
I'm new to contributing to pandas, and I'm not sure where to add this test.
Let me know if this place is inappropriate. | https://api.github.com/repos/pandas-dev/pandas/pulls/35799 | 2020-08-19T08:19:44Z | 2020-08-21T22:42:51Z | 2020-08-21T22:42:51Z | 2020-08-21T22:42:56Z |
Bump asv Python version | diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json
index 4583fac85b776..1863a17e3d5f7 100644
--- a/asv_bench/asv.conf.json
+++ b/asv_bench/asv.conf.json
@@ -26,7 +26,7 @@
// The Pythons you'd like to test against. If not provided, defaults
// to the current version of Python used to run `asv`.
// "pythons": ["2.7", "3.4"],
- "pythons": ["3.6"],
+ "pythons": ["3.8"],
// The matrix of dependencies to test. Each key is the name of a
// package (in PyPI) and the values are version numbers. An empty
| Got this error trying to run the asvs locally and bumping the Python version in asv.conf.json fixed it:
```
STDOUT -------->
Processing /Users/danielsaxton/pandas/asv_bench/env/a36d556a9d1611aba4092dc48036d261/project
Preparing wheel metadata: started
Preparing wheel metadata: finished with status 'done'
STDERR -------->
ERROR: Package 'pandas' requires a different Python: 3.6.10 not in '>=3.7.1'
```
Let me know if this is needed / correct in general or if it was just a thing with my machine.
cc @TomAugspurger
Closes https://github.com/pandas-dev/pandas/issues/34677 | https://api.github.com/repos/pandas-dev/pandas/pulls/35798 | 2020-08-19T02:45:00Z | 2020-08-26T13:57:41Z | 2020-08-26T13:57:41Z | 2020-08-26T17:06:12Z |
BUG: issubclass check with dtype instead of type, closes GH#24883 | diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst
index 81acd567027e5..7bd547bf03a87 100644
--- a/doc/source/whatsnew/v1.1.2.rst
+++ b/doc/source/whatsnew/v1.1.2.rst
@@ -24,7 +24,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
-
+- Bug in :meth:`DataFrame.eval` with ``object`` dtype column binary operations (:issue:`35794`)
-
-
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py
index bc9ff7c44b689..e55df1e1d8155 100644
--- a/pandas/core/computation/ops.py
+++ b/pandas/core/computation/ops.py
@@ -481,13 +481,21 @@ def stringify(value):
self.lhs.update(v)
def _disallow_scalar_only_bool_ops(self):
+ rhs = self.rhs
+ lhs = self.lhs
+
+ # GH#24883 unwrap dtype if necessary to ensure we have a type object
+ rhs_rt = rhs.return_type
+ rhs_rt = getattr(rhs_rt, "type", rhs_rt)
+ lhs_rt = lhs.return_type
+ lhs_rt = getattr(lhs_rt, "type", lhs_rt)
if (
- (self.lhs.is_scalar or self.rhs.is_scalar)
+ (lhs.is_scalar or rhs.is_scalar)
and self.op in _bool_ops_dict
and (
not (
- issubclass(self.rhs.return_type, (bool, np.bool_))
- and issubclass(self.lhs.return_type, (bool, np.bool_))
+ issubclass(rhs_rt, (bool, np.bool_))
+ and issubclass(lhs_rt, (bool, np.bool_))
)
)
):
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index 628b955a1de92..56d178daee7fd 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -160,6 +160,13 @@ def test_eval_resolvers_as_list(self):
assert df.eval("a + b", resolvers=[dict1, dict2]) == dict1["a"] + dict2["b"]
assert pd.eval("a + b", resolvers=[dict1, dict2]) == dict1["a"] + dict2["b"]
+ def test_eval_object_dtype_binop(self):
+ # GH#24883
+ df = pd.DataFrame({"a1": ["Y", "N"]})
+ res = df.eval("c = ((a1 == 'Y') & True)")
+ expected = pd.DataFrame({"a1": ["Y", "N"], "c": [True, False]})
+ tm.assert_frame_equal(res, expected)
+
class TestDataFrameQueryWithMultiIndex:
def test_query_with_named_multiindex(self, parser, engine):
| - [x] closes #24883
- [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/35794 | 2020-08-18T23:00:56Z | 2020-08-21T21:53:51Z | 2020-08-21T21:53:51Z | 2020-08-27T09:18:49Z |
CLN/BUG: Clean/Simplify _wrap_applied_output | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index adc1806523d6e..55570341cf4e8 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -254,6 +254,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrameGroupBy.apply` that would some times throw an erroneous ``ValueError`` if the grouping axis had duplicate entries (:issue:`16646`)
- Bug when combining methods :meth:`DataFrame.groupby` with :meth:`DataFrame.resample` and :meth:`DataFrame.interpolate` raising an ``TypeError`` (:issue:`35325`)
- Bug in :meth:`DataFrameGroupBy.apply` where a non-nuisance grouping column would be dropped from the output columns if another groupby method was called before ``.apply()`` (:issue:`34656`)
+- Bug in :meth:`DataFrameGroupby.apply` would drop a :class:`CategoricalIndex` when grouped on. (:issue:`35792`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 70a8379de64e9..2afa56b50c3c7 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1197,57 +1197,25 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if len(keys) == 0:
return self.obj._constructor(index=keys)
- key_names = self.grouper.names
-
# GH12824
first_not_none = next(com.not_none(*values), None)
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.
+ # GH9684 - All values are None, return an empty frame.
return self.obj._constructor()
elif isinstance(first_not_none, DataFrame):
return self._concat_objects(keys, values, not_indexed_same=not_indexed_same)
else:
- if len(self.grouper.groupings) > 1:
- key_index = self.grouper.result_index
-
- else:
- ping = self.grouper.groupings[0]
- if len(keys) == ping.ngroups:
- key_index = ping.group_index
- key_index.name = key_names[0]
-
- key_lookup = Index(keys)
- indexer = key_lookup.get_indexer(key_index)
-
- # reorder the values
- values = [values[i] for i in indexer]
-
- # update due to the potential reorder
- first_not_none = next(com.not_none(*values), None)
- else:
-
- key_index = Index(keys, name=key_names[0])
-
- # don't use the key indexer
- if not self.as_index:
- key_index = None
+ key_index = self.grouper.result_index if self.as_index else None
- # make Nones an empty object
- if first_not_none is None:
- return self.obj._constructor()
- elif isinstance(first_not_none, NDFrame):
+ if isinstance(first_not_none, Series):
# this is to silence a DeprecationWarning
# TODO: Remove when default dtype of empty Series is object
kwargs = first_not_none._construct_axes_dict()
- if isinstance(first_not_none, Series):
- backup = create_series_with_explicit_dtype(
- **kwargs, dtype_if_empty=object
- )
- else:
- backup = first_not_none._constructor(**kwargs)
+ backup = create_series_with_explicit_dtype(
+ **kwargs, dtype_if_empty=object
+ )
values = [x if (x is not None) else backup for x in values]
@@ -1256,7 +1224,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
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])
+ all_indexed_same = all_indexes_same((x.index for x in values))
singular_series = len(values) == 1 and applied_index.nlevels == 1
# GH3596
@@ -1288,7 +1256,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# GH 8467
return self._concat_objects(keys, values, not_indexed_same=True)
- if self.axis == 0 and isinstance(v, ABCSeries):
# GH6124 if the list of Series have a consistent name,
# then propagate that name to the result.
index = v.index.copy()
@@ -1301,34 +1268,27 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if len(names) == 1:
index.name = list(names)[0]
- # normally use vstack as its faster than concat
- # and if we have mi-columns
- if (
- isinstance(v.index, MultiIndex)
- or key_index is None
- or isinstance(key_index, MultiIndex)
- ):
- stacked_values = np.vstack([np.asarray(v) for v in values])
- result = self.obj._constructor(
- stacked_values, index=key_index, columns=index
- )
- else:
- # GH5788 instead of stacking; concat gets the
- # dtypes correct
- from pandas.core.reshape.concat import concat
-
- result = concat(
- values,
- keys=key_index,
- names=key_index.names,
- axis=self.axis,
- ).unstack()
- result.columns = index
- elif isinstance(v, ABCSeries):
+ # Combine values
+ # vstack+constructor is faster than concat and handles MI-columns
stacked_values = np.vstack([np.asarray(v) for v in values])
+
+ if self.axis == 0:
+ index = key_index
+ columns = v.index.copy()
+ if columns.name is None:
+ # GH6124 - propagate name of Series when it's consistent
+ names = {v.name for v in values}
+ if len(names) == 1:
+ columns.name = list(names)[0]
+ else:
+ index = v.index
+ columns = key_index
+ stacked_values = stacked_values.T
+
result = self.obj._constructor(
- stacked_values.T, index=v.index, columns=key_index
+ stacked_values, index=index, columns=columns
)
+
elif not self.as_index:
# We add grouping column below, so create a frame here
result = DataFrame(
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index 30cc8cf480dcf..d352b001f5d2a 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -297,15 +297,16 @@ def all_indexes_same(indexes):
Parameters
----------
- indexes : list of Index objects
+ indexes : iterable of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise.
"""
- first = indexes[0]
- for index in indexes[1:]:
+ itr = iter(indexes)
+ first = next(itr)
+ for index in itr:
if not first.equals(index):
return False
return True
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index ee38722ffb8ce..a1dcb28a32c6c 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -861,13 +861,14 @@ def test_apply_multi_level_name(category):
b = [1, 2] * 5
if category:
b = pd.Categorical(b, categories=[1, 2, 3])
+ expected_index = pd.CategoricalIndex([1, 2], categories=[1, 2, 3], name="B")
+ else:
+ expected_index = pd.Index([1, 2], name="B")
df = pd.DataFrame(
{"A": np.arange(10), "B": b, "C": list(range(10)), "D": list(range(10))}
).set_index(["A", "B"])
result = df.groupby("B").apply(lambda x: x.sum())
- expected = pd.DataFrame(
- {"C": [20, 25], "D": [20, 25]}, index=pd.Index([1, 2], name="B")
- )
+ expected = pd.DataFrame({"C": [20, 25], "D": [20, 25]}, index=expected_index)
tm.assert_frame_equal(result, expected)
assert df.index.names == ["A", "B"]
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
First part of #35412. I could not find a relevant issue for the test change/whatsnew update. | https://api.github.com/repos/pandas-dev/pandas/pulls/35792 | 2020-08-18T21:54:42Z | 2020-08-26T03:21:44Z | 2020-08-26T03:21:44Z | 2020-10-26T15:42:17Z |
Backport PR #35774 on branch 1.1.x (REGR: follow-up to return copy with df.interpolate on empty DataFrame) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3a386a8df7075..8bd1dbea4696f 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6800,7 +6800,7 @@ def interpolate(
obj = self.T if should_transpose else self
if obj.empty:
- return self
+ return self.copy()
if method not in fillna_methods:
axis = self._info_axis_number
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index 3c9d79397e4bd..6b86a13fcf1b9 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -38,6 +38,7 @@ def test_interp_empty(self):
# https://github.com/pandas-dev/pandas/issues/35598
df = DataFrame()
result = df.interpolate()
+ assert result is not df
expected = df
tm.assert_frame_equal(result, expected)
| Backport PR #35774: REGR: follow-up to return copy with df.interpolate on empty DataFrame | https://api.github.com/repos/pandas-dev/pandas/pulls/35789 | 2020-08-18T13:06:29Z | 2020-08-18T14:12:19Z | 2020-08-18T14:12:19Z | 2020-08-18T14:12:20Z |
DOC: clean v1.1.1 release notes | diff --git a/doc/source/whatsnew/v1.1.1.rst b/doc/source/whatsnew/v1.1.1.rst
index ff5bbccf63ffe..43ffed273adbc 100644
--- a/doc/source/whatsnew/v1.1.1.rst
+++ b/doc/source/whatsnew/v1.1.1.rst
@@ -1,7 +1,7 @@
.. _whatsnew_111:
-What's new in 1.1.1 (?)
------------------------
+What's new in 1.1.1 (August XX, 2020)
+-------------------------------------
These are the changes in pandas 1.1.1. See :ref:`release` for a full changelog
including other versions of pandas.
@@ -15,20 +15,23 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`CategoricalIndex.format` where, when stringified scalars had different lengths, the shorter string would be right-filled with spaces, so it had the same length as the longest string (:issue:`35439`)
+- Fixed regression in :meth:`Series.truncate` when trying to truncate a single-element series (:issue:`35544`)
- Fixed regression where :meth:`DataFrame.to_numpy` would raise a ``RuntimeError`` for mixed dtypes when converting to ``str`` (:issue:`35455`)
- Fixed regression where :func:`read_csv` would raise a ``ValueError`` when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`35493`)
- Fixed regression where :func:`pandas.testing.assert_series_equal` would raise an error when non-numeric dtypes were passed with ``check_exact=True`` (:issue:`35446`)
-- Fixed regression in :class:`pandas.core.groupby.RollingGroupby` where column selection was ignored (:issue:`35486`)
-- Fixed regression where :meth:`DataFrame.interpolate` would raise a ``TypeError`` when the :class:`DataFrame` was empty (:issue:`35598`).
+- Fixed regression in ``.groupby(..).rolling(..)`` where column selection was ignored (:issue:`35486`)
+- Fixed regression where :meth:`DataFrame.interpolate` would raise a ``TypeError`` when the :class:`DataFrame` was empty (:issue:`35598`)
- Fixed regression in :meth:`DataFrame.shift` with ``axis=1`` and heterogeneous dtypes (:issue:`35488`)
- Fixed regression in :meth:`DataFrame.diff` with read-only data (:issue:`35559`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a segfault would occur with ``center=True`` and an odd number of values (:issue:`35552`)
- Fixed regression in :meth:`DataFrame.apply` where functions that altered the input in-place only operated on a single row (:issue:`35462`)
- Fixed regression in :meth:`DataFrame.reset_index` would raise a ``ValueError`` on empty :class:`DataFrame` with a :class:`MultiIndex` with a ``datetime64`` dtype level (:issue:`35606`, :issue:`35657`)
-- Fixed regression where :meth:`DataFrame.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
+- Fixed regression where :func:`pandas.merge_asof` would raise a ``UnboundLocalError`` when ``left_index`` , ``right_index`` and ``tolerance`` were set (:issue:`35558`)
- Fixed regression in ``.groupby(..).rolling(..)`` where a custom ``BaseIndexer`` would be ignored (:issue:`35557`)
- Fixed regression in :meth:`DataFrame.replace` and :meth:`Series.replace` where compiled regular expressions would be ignored during replacement (:issue:`35680`)
-- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.agg` where a list of functions would produce the wrong results if at least one of the functions did not aggregate. (:issue:`35490`)
+- Fixed regression in :meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` where a list of functions would produce the wrong results if at least one of the functions did not aggregate (:issue:`35490`)
+- Fixed memory usage issue when instantiating large :class:`pandas.arrays.StringArray` (:issue:`35499`)
.. ---------------------------------------------------------------------------
@@ -37,50 +40,11 @@ Fixed regressions
Bug fixes
~~~~~~~~~
-- Bug in ``Styler`` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`).
-- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`).
-
-Categorical
-^^^^^^^^^^^
-
-- Bug in :meth:`CategoricalIndex.format` where, when stringified scalars had different lengths, the shorter string would be right-filled with spaces, so it had the same length as the longest string (:issue:`35439`)
-
-
-**Datetimelike**
-
--
--
-
-**Timedelta**
-
+- Bug in :class:`~pandas.io.formats.style.Styler` whereby `cell_ids` argument had no effect due to other recent changes (:issue:`35588`) (:issue:`35663`)
+- Bug in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` where extension dtypes were not ignored when ``check_dtypes`` was set to ``False`` (:issue:`35715`)
- Bug in :meth:`to_timedelta` fails when arg is a :class:`Series` with `Int64` dtype containing null values (:issue:`35574`)
-
-
-**Numeric**
-
--
--
-
-**Groupby/resample/rolling**
-
-- Bug in :class:`pandas.core.groupby.RollingGroupby` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
-
-**Plotting**
-
--
-
-**Indexing**
-
-- Bug in :meth:`Series.truncate` when trying to truncate a single-element series (:issue:`35544`)
-
-**DataFrame**
+- Bug in ``.groupby(..).rolling(..)`` where passing ``closed`` with column selection would raise a ``ValueError`` (:issue:`35549`)
- Bug in :class:`DataFrame` constructor failing to raise ``ValueError`` in some cases when data and index have mismatched lengths (:issue:`33437`)
--
-
-**Strings**
-
-- fix memory usage issue when instantiating large :class:`pandas.arrays.StringArray` (:issue:`35499`)
-
.. ---------------------------------------------------------------------------
| https://api.github.com/repos/pandas-dev/pandas/pulls/35787 | 2020-08-18T12:12:49Z | 2020-08-19T09:48:42Z | 2020-08-19T09:48:42Z | 2020-08-19T09:52:45Z | |
CLN: remove unused variable | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 1f0cdbd07560f..166631e69f523 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1031,7 +1031,6 @@ def _cython_agg_blocks(
data = data.get_numeric_data(copy=False)
agg_blocks: List["Block"] = []
- deleted_items: List[np.ndarray] = []
no_result = object()
@@ -1133,7 +1132,6 @@ def blk_func(block: "Block") -> List["Block"]:
# continue and exclude the block
# NotImplementedError -> "ohlc" with wrong dtype
skipped.append(i)
- deleted_items.append(block.mgr_locs.as_array)
else:
agg_blocks.extend(nbs)
| https://api.github.com/repos/pandas-dev/pandas/pulls/35783 | 2020-08-18T04:08:03Z | 2020-08-18T13:05:30Z | 2020-08-18T13:05:30Z | 2020-08-18T15:49:35Z | |
CI: unpin numpy and matplotlib #35779 | diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 5bc87bca87211..8ce4b30c717a4 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -668,6 +668,7 @@ A ``ValueError`` will be raised if there are any negative values in your data.
plt.figure()
.. ipython:: python
+ :okwarning:
series = pd.Series(3 * np.random.rand(4),
index=['a', 'b', 'c', 'd'], name='series')
@@ -742,6 +743,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc
plt.figure()
.. ipython:: python
+ :okwarning:
series = pd.Series([0.1] * 4, index=['a', 'b', 'c', 'd'], name='series2')
diff --git a/environment.yml b/environment.yml
index 1e51470d43d36..aaabf09b8f190 100644
--- a/environment.yml
+++ b/environment.yml
@@ -3,8 +3,7 @@ channels:
- conda-forge
dependencies:
# required
- # Pin numpy<1.19 until MPL 3.3.0 is released.
- - numpy>=1.16.5,<1.19.0
+ - numpy>=1.16.5
- python=3
- python-dateutil>=2.7.3
- pytz
@@ -73,7 +72,7 @@ dependencies:
- ipykernel
- ipython>=7.11.1
- jinja2 # pandas.Styler
- - matplotlib>=2.2.2,<3.3.0 # pandas.plotting, Series.plot, DataFrame.plot
+ - matplotlib>=2.2.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.6.8
- scipy>=1.2
- numba>=0.46.0
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1587dd8798ec3..c16919e523264 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2600,7 +2600,7 @@ def to_html(
1 column_2 1000000 non-null object
2 column_3 1000000 non-null object
dtypes: object(3)
- memory usage: 188.8 MB"""
+ memory usage: 165.9 MB"""
),
see_also_sub=(
"""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e8bf87a39b572..cd2db659fbd0e 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4637,7 +4637,7 @@ def memory_usage(self, index=True, deep=False):
>>> s.memory_usage()
144
>>> s.memory_usage(deep=True)
- 260
+ 244
"""
v = super().memory_usage(deep=deep)
if index:
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py
index 53ef97bbe9a72..b33daf39de37c 100644
--- a/pandas/plotting/_matplotlib/boxplot.py
+++ b/pandas/plotting/_matplotlib/boxplot.py
@@ -294,7 +294,7 @@ def maybe_color_bp(bp, **kwds):
def plot_group(keys, values, ax):
keys = [pprint_thing(x) for x in keys]
- values = [np.asarray(remove_na_arraylike(v)) for v in values]
+ values = [np.asarray(remove_na_arraylike(v), dtype=object) for v in values]
bp = ax.boxplot(values, **kwds)
if fontsize is not None:
ax.tick_params(axis="both", labelsize=fontsize)
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 66e72641cd5bb..3d0778b74ccbd 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -1,7 +1,7 @@
# This file is auto-generated from environment.yml, do not modify.
# See that file for comments about the need/usage of each dependency.
-numpy>=1.16.5,<1.19.0
+numpy>=1.16.5
python-dateutil>=2.7.3
pytz
asv
@@ -47,7 +47,7 @@ bottleneck>=1.2.1
ipykernel
ipython>=7.11.1
jinja2
-matplotlib>=2.2.2,<3.3.0
+matplotlib>=2.2.2
numexpr>=2.6.8
scipy>=1.2
numba>=0.46.0
| - [x] closes #35779
| https://api.github.com/repos/pandas-dev/pandas/pulls/35780 | 2020-08-18T01:10:26Z | 2020-08-19T20:40:05Z | 2020-08-19T20:40:05Z | 2020-08-19T21:38:01Z |
Added numba as an argument | diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst
index d7875e5b8d861..151ef36be7c98 100644
--- a/doc/source/user_guide/computation.rst
+++ b/doc/source/user_guide/computation.rst
@@ -361,6 +361,9 @@ compute the mean absolute deviation on a rolling basis:
@savefig rolling_apply_ex.png
s.rolling(window=60).apply(mad, raw=True).plot(style='k')
+Using the Numba engine
+~~~~~~~~~~~~~~~~~~~~~~
+
.. versionadded:: 1.0
Additionally, :meth:`~Rolling.apply` can leverage `Numba <https://numba.pydata.org/>`__
diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst
index 24fcb369804c6..9e101c1a20371 100644
--- a/doc/source/user_guide/enhancingperf.rst
+++ b/doc/source/user_guide/enhancingperf.rst
@@ -373,6 +373,13 @@ nicer interface by passing/returning pandas objects.
In this example, using Numba was faster than Cython.
+Numba as an argument
+~~~~~~~~~~~~~~~~~~~~
+
+Additionally, we can leverage the power of `Numba <https://numba.pydata.org/>`__
+by calling it as an argument in :meth:`~Rolling.apply`. See :ref:`Computation tools
+<stats.rolling_apply>` for an extensive example.
+
Vectorize
~~~~~~~~~
| - [x] closes #35550
- [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/35778 | 2020-08-17T23:30:02Z | 2020-09-01T23:52:09Z | 2020-09-01T23:52:08Z | 2020-09-02T08:08:16Z |
BUG: DataFrame.apply with result_type=reduce incorrect index | diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst
index 7bd547bf03a87..c1b73c60be92b 100644
--- a/doc/source/whatsnew/v1.1.2.rst
+++ b/doc/source/whatsnew/v1.1.2.rst
@@ -25,6 +25,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
- Bug in :meth:`DataFrame.eval` with ``object`` dtype column binary operations (:issue:`35794`)
+- Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`)
-
-
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 6d44cf917a07a..99a9e1377563c 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -340,7 +340,10 @@ def wrap_results_for_axis(
if self.result_type == "reduce":
# e.g. test_apply_dict GH#8735
- return self.obj._constructor_sliced(results)
+ res = self.obj._constructor_sliced(results)
+ res.index = res_index
+ return res
+
elif self.result_type is None and all(
isinstance(x, dict) for x in results.values()
):
diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py
index 538978358c8e7..5a1e448beb40f 100644
--- a/pandas/tests/frame/apply/test_frame_apply.py
+++ b/pandas/tests/frame/apply/test_frame_apply.py
@@ -1541,3 +1541,12 @@ def func(row):
tm.assert_frame_equal(result, expected)
tm.assert_frame_equal(df, result)
+
+
+def test_apply_empty_list_reduce():
+ # GH#35683 get columns correct
+ df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=["a", "b"])
+
+ result = df.apply(lambda x: [], result_type="reduce")
+ expected = pd.Series({"a": [], "b": []}, dtype=object)
+ tm.assert_series_equal(result, expected)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This may xref #35683 pending discussion there. | https://api.github.com/repos/pandas-dev/pandas/pulls/35777 | 2020-08-17T23:18:40Z | 2020-08-22T02:04:21Z | 2020-08-22T02:04:21Z | 2021-11-20T23:22:44Z |
Changed 'int' type to 'integer' in to_numeric docstring | diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index d8db196e4b92f..1531f7b292365 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -234,7 +234,7 @@ class SparseArray(PandasObject, ExtensionArray, ExtensionOpsMixin):
3. ``data.dtype.fill_value`` if `fill_value` is None and `dtype`
is not a ``SparseDtype`` and `data` is a ``SparseArray``.
- kind : {'int', 'block'}, default 'int'
+ kind : {'integer', 'block'}, default 'integer'
The type of storage for sparse locations.
* 'block': Stores a `block` and `block_length` for each
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index 41548931f17f8..cff4695603d06 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -40,13 +40,13 @@ def to_numeric(arg, errors="raise", downcast=None):
- If 'raise', then invalid parsing will raise an exception.
- If 'coerce', then invalid parsing will be set as NaN.
- If 'ignore', then invalid parsing will return the input.
- downcast : {'int', 'signed', 'unsigned', 'float'}, default None
+ downcast : {'integer', 'signed', 'unsigned', 'float'}, default None
If not None, and if the data has been successfully cast to a
numerical dtype (or if the data was numeric to begin with),
downcast that resulting data to the smallest numerical dtype
possible according to the following rules:
- - 'int' or 'signed': smallest signed int dtype (min.: np.int8)
+ - 'integer' or 'signed': smallest signed int dtype (min.: np.int8)
- 'unsigned': smallest unsigned int dtype (min.: np.uint8)
- 'float': smallest float dtype (min.: np.float32)
| - [x] closes #35760
- [ ] 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/35776 | 2020-08-17T22:44:38Z | 2020-08-19T13:16:42Z | 2020-08-19T13:16:42Z | 2020-08-19T13:16:56Z |
TST: Verify whether read-only datetime64 array can be factorized (35650) | diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index a080bf0feaebc..04ad5b479016f 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -251,6 +251,19 @@ def test_object_factorize(self, writable):
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_numpy_array_equal(uniques, expected_uniques)
+ def test_datetime64_factorize(self, writable):
+ # GH35650 Verify whether read-only datetime64 array can be factorized
+ data = np.array([np.datetime64("2020-01-01T00:00:00.000")])
+ data.setflags(write=writable)
+ expected_codes = np.array([0], dtype=np.int64)
+ expected_uniques = np.array(
+ ["2020-01-01T00:00:00.000000000"], dtype="datetime64[ns]"
+ )
+
+ codes, uniques = pd.factorize(data)
+ tm.assert_numpy_array_equal(codes, expected_codes)
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
+
def test_deprecate_order(self):
# gh 19727 - check warning is raised for deprecated keyword, order.
# Test not valid once order keyword is removed.
| - [x] closes #35650
- [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/35775 | 2020-08-17T22:21:28Z | 2020-08-26T12:44:26Z | 2020-08-26T12:44:25Z | 2020-08-26T12:44:51Z |
REGR: follow-up to return copy with df.interpolate on empty DataFrame | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9cbe2f714fd57..fe412bc0ce937 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6893,7 +6893,7 @@ def interpolate(
obj = self.T if should_transpose else self
if obj.empty:
- return self
+ return self.copy()
if method not in fillna_methods:
axis = self._info_axis_number
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index 3c9d79397e4bd..6b86a13fcf1b9 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -38,6 +38,7 @@ def test_interp_empty(self):
# https://github.com/pandas-dev/pandas/issues/35598
df = DataFrame()
result = df.interpolate()
+ assert result is not df
expected = df
tm.assert_frame_equal(result, expected)
| follow-up to #35543 | https://api.github.com/repos/pandas-dev/pandas/pulls/35774 | 2020-08-17T19:27:18Z | 2020-08-18T12:54:56Z | 2020-08-18T12:54:56Z | 2020-08-18T13:06:35Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.