title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
TST/CLN: Tests parametrizations 3 | diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py
index 45dc612148f40..7e0b8dc7282e4 100644
--- a/pandas/tests/plotting/frame/test_frame.py
+++ b/pandas/tests/plotting/frame/test_frame.py
@@ -1199,12 +1199,10 @@ def test_hist_df_orientation(self):
axes = df.plot.hist(rot=50, fontsize=8, orientation="horizontal")
_check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8)
- @pytest.mark.parametrize(
- "weights", [0.1 * np.ones(shape=(100,)), 0.1 * np.ones(shape=(100, 2))]
- )
- def test_hist_weights(self, weights):
+ @pytest.mark.parametrize("weight_shape", [(100,), (100, 2)])
+ def test_hist_weights(self, weight_shape):
# GH 33173
-
+ weights = 0.1 * np.ones(shape=weight_shape)
df = DataFrame(
dict(zip(["A", "B"], np.random.default_rng(2).standard_normal((2, 100))))
)
diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py
index ff1edd323ef28..4f14f1e43cf29 100644
--- a/pandas/tests/plotting/frame/test_frame_color.py
+++ b/pandas/tests/plotting/frame/test_frame_color.py
@@ -30,11 +30,10 @@ def _check_colors_box(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=Non
class TestDataFrameColor:
- @pytest.mark.parametrize(
- "color", ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
- )
+ @pytest.mark.parametrize("color", list(range(10)))
def test_mpl2_color_cycle_str(self, color):
# GH 15516
+ color = f"C{color}"
df = DataFrame(
np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]
)
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index f370d32d0caa9..20749c7ed90e8 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -1144,18 +1144,7 @@ def test_timedelta64_analytics(self):
expected = Timedelta("1 days")
assert result == expected
- @pytest.mark.parametrize(
- "test_input,error_type",
- [
- (Series([], dtype="float64"), ValueError),
- # For strings, or any Series with dtype 'O'
- (Series(["foo", "bar", "baz"]), TypeError),
- (Series([(1,), (2,)]), TypeError),
- # For mixed data types
- (Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"]), TypeError),
- ],
- )
- def test_assert_idxminmax_empty_raises(self, test_input, error_type):
+ def test_assert_idxminmax_empty_raises(self):
"""
Cases where ``Series.argmax`` and related should raise an exception
"""
@@ -1294,13 +1283,14 @@ def test_minmax_nat_series(self, nat_ser):
@pytest.mark.parametrize(
"nat_df",
[
- DataFrame([NaT, NaT]),
- DataFrame([NaT, Timedelta("nat")]),
- DataFrame([Timedelta("nat"), Timedelta("nat")]),
+ [NaT, NaT],
+ [NaT, Timedelta("nat")],
+ [Timedelta("nat"), Timedelta("nat")],
],
)
def test_minmax_nat_dataframe(self, nat_df):
# GH#23282
+ nat_df = DataFrame(nat_df)
assert nat_df.min()[0] is NaT
assert nat_df.max()[0] is NaT
assert nat_df.min(skipna=False)[0] is NaT
@@ -1399,14 +1389,10 @@ class TestSeriesMode:
# were moved from a series-specific test file, _not_ that these tests are
# intended long-term to be series-specific
- @pytest.mark.parametrize(
- "dropna, expected",
- [(True, Series([], dtype=np.float64)), (False, Series([], dtype=np.float64))],
- )
- def test_mode_empty(self, dropna, expected):
+ def test_mode_empty(self, dropna):
s = Series([], dtype=np.float64)
result = s.mode(dropna)
- tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result, s)
@pytest.mark.parametrize(
"dropna, data, expected",
@@ -1619,23 +1605,24 @@ def test_mode_boolean_with_na(self):
[
(
[0, 1j, 1, 1, 1 + 1j, 1 + 2j],
- Series([1], dtype=np.complex128),
+ [1],
np.complex128,
),
(
[0, 1j, 1, 1, 1 + 1j, 1 + 2j],
- Series([1], dtype=np.complex64),
+ [1],
np.complex64,
),
(
[1 + 1j, 2j, 1 + 1j],
- Series([1 + 1j], dtype=np.complex128),
+ [1 + 1j],
np.complex128,
),
],
)
def test_single_mode_value_complex(self, array, expected, dtype):
result = Series(array, dtype=dtype).mode()
+ expected = Series(expected, dtype=dtype)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
@@ -1644,12 +1631,12 @@ def test_single_mode_value_complex(self, array, expected, dtype):
(
# no modes
[0, 1j, 1, 1 + 1j, 1 + 2j],
- Series([0j, 1j, 1 + 0j, 1 + 1j, 1 + 2j], dtype=np.complex128),
+ [0j, 1j, 1 + 0j, 1 + 1j, 1 + 2j],
np.complex128,
),
(
[1 + 1j, 2j, 1 + 1j, 2j, 3],
- Series([2j, 1 + 1j], dtype=np.complex64),
+ [2j, 1 + 1j],
np.complex64,
),
],
@@ -1659,4 +1646,5 @@ def test_multimode_complex(self, array, expected, dtype):
# mode tries to sort multimodal series.
# Complex numbers are sorted by their magnitude
result = Series(array, dtype=dtype).mode()
+ expected = Series(expected, dtype=dtype)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/reshape/concat/test_series.py b/pandas/tests/reshape/concat/test_series.py
index c12b835cb61e1..bdc64fe826cc9 100644
--- a/pandas/tests/reshape/concat/test_series.py
+++ b/pandas/tests/reshape/concat/test_series.py
@@ -128,11 +128,10 @@ def test_concat_series_axis1_same_names_ignore_index(self):
tm.assert_index_equal(result.columns, expected, exact=True)
- @pytest.mark.parametrize(
- "s1name,s2name", [(np.int64(190), (43, 0)), (190, (43, 0))]
- )
- def test_concat_series_name_npscalar_tuple(self, s1name, s2name):
+ @pytest.mark.parametrize("s1name", [np.int64(190), 190])
+ def test_concat_series_name_npscalar_tuple(self, s1name):
# GH21015
+ s2name = (43, 0)
s1 = Series({"a": 1, "b": 2}, name=s1name)
s2 = Series({"c": 5, "d": 6}, name=s2name)
result = concat([s1, s2])
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 72e6457e65e3c..b9b1224194295 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1466,10 +1466,8 @@ def _check_merge(x, y):
class TestMergeDtypes:
- @pytest.mark.parametrize(
- "right_vals", [["foo", "bar"], Series(["foo", "bar"]).astype("category")]
- )
- def test_different(self, right_vals):
+ @pytest.mark.parametrize("dtype", [object, "category"])
+ def test_different(self, dtype):
left = DataFrame(
{
"A": ["foo", "bar"],
@@ -1480,6 +1478,7 @@ def test_different(self, right_vals):
"F": Series([1, 2], dtype="int32"),
}
)
+ right_vals = Series(["foo", "bar"], dtype=dtype)
right = DataFrame({"A": right_vals})
# GH 9780
@@ -2311,19 +2310,15 @@ def test_merge_suffix(col1, col2, kwargs, expected_cols):
[
(
"right",
- DataFrame(
- {"A": [100, 200, 300], "B1": [60, 70, np.nan], "B2": [600, 700, 800]}
- ),
+ {"A": [100, 200, 300], "B1": [60, 70, np.nan], "B2": [600, 700, 800]},
),
(
"outer",
- DataFrame(
- {
- "A": [1, 100, 200, 300],
- "B1": [80, 60, 70, np.nan],
- "B2": [np.nan, 600, 700, 800],
- }
- ),
+ {
+ "A": [1, 100, 200, 300],
+ "B1": [80, 60, 70, np.nan],
+ "B2": [np.nan, 600, 700, 800],
+ },
),
],
)
@@ -2331,6 +2326,7 @@ def test_merge_duplicate_suffix(how, expected):
left_df = DataFrame({"A": [100, 200, 1], "B": [60, 70, 80]})
right_df = DataFrame({"A": [100, 200, 300], "B": [600, 700, 800]})
result = merge(left_df, right_df, on="A", how=how, suffixes=("_x", "_x"))
+ expected = DataFrame(expected)
expected.columns = ["A", "B_x", "B_x"]
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py
index 00df8064d5190..b0efbc253c04e 100644
--- a/pandas/tests/reshape/merge/test_merge_asof.py
+++ b/pandas/tests/reshape/merge/test_merge_asof.py
@@ -3099,7 +3099,7 @@ def test_merge_groupby_multiple_column_with_categorical_column(self):
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
- "func", [lambda x: x, lambda x: to_datetime(x)], ids=["numeric", "datetime"]
+ "func", [lambda x: x, to_datetime], ids=["numeric", "datetime"]
)
@pytest.mark.parametrize("side", ["left", "right"])
def test_merge_on_nans(self, func, side):
diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py
index abd61026b4e37..db71a732b44e3 100644
--- a/pandas/tests/reshape/merge/test_merge_ordered.py
+++ b/pandas/tests/reshape/merge/test_merge_ordered.py
@@ -135,54 +135,50 @@ def test_doc_example(self):
"left, right, on, left_by, right_by, expected",
[
(
- DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),
- DataFrame({"T": [2], "E": [1]}),
+ {"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]},
+ {"T": [2], "E": [1]},
["T"],
["G", "H"],
None,
- DataFrame(
- {
- "G": ["g"] * 3,
- "H": ["h"] * 3,
- "T": [1, 2, 3],
- "E": [np.nan, 1.0, np.nan],
- }
- ),
+ {
+ "G": ["g"] * 3,
+ "H": ["h"] * 3,
+ "T": [1, 2, 3],
+ "E": [np.nan, 1.0, np.nan],
+ },
),
(
- DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),
- DataFrame({"T": [2], "E": [1]}),
+ {"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]},
+ {"T": [2], "E": [1]},
"T",
["G", "H"],
None,
- DataFrame(
- {
- "G": ["g"] * 3,
- "H": ["h"] * 3,
- "T": [1, 2, 3],
- "E": [np.nan, 1.0, np.nan],
- }
- ),
+ {
+ "G": ["g"] * 3,
+ "H": ["h"] * 3,
+ "T": [1, 2, 3],
+ "E": [np.nan, 1.0, np.nan],
+ },
),
(
- DataFrame({"T": [2], "E": [1]}),
- DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),
+ {"T": [2], "E": [1]},
+ {"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]},
["T"],
None,
["G", "H"],
- DataFrame(
- {
- "T": [1, 2, 3],
- "E": [np.nan, 1.0, np.nan],
- "G": ["g"] * 3,
- "H": ["h"] * 3,
- }
- ),
+ {
+ "T": [1, 2, 3],
+ "E": [np.nan, 1.0, np.nan],
+ "G": ["g"] * 3,
+ "H": ["h"] * 3,
+ },
),
],
)
def test_list_type_by(self, left, right, on, left_by, right_by, expected):
# GH 35269
+ left = DataFrame(left)
+ right = DataFrame(right)
result = merge_ordered(
left=left,
right=right,
@@ -190,6 +186,7 @@ def test_list_type_by(self, left, right, on, left_by, right_by, expected):
left_by=left_by,
right_by=right_by,
)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/test_from_dummies.py b/pandas/tests/reshape/test_from_dummies.py
index f9a03222c8057..ba71bb24e8a16 100644
--- a/pandas/tests/reshape/test_from_dummies.py
+++ b/pandas/tests/reshape/test_from_dummies.py
@@ -298,32 +298,32 @@ def test_no_prefix_string_cats_contains_get_dummies_NaN_column():
[
pytest.param(
"c",
- DataFrame({"": ["a", "b", "c"]}),
+ {"": ["a", "b", "c"]},
id="default_category is a str",
),
pytest.param(
1,
- DataFrame({"": ["a", "b", 1]}),
+ {"": ["a", "b", 1]},
id="default_category is a int",
),
pytest.param(
1.25,
- DataFrame({"": ["a", "b", 1.25]}),
+ {"": ["a", "b", 1.25]},
id="default_category is a float",
),
pytest.param(
0,
- DataFrame({"": ["a", "b", 0]}),
+ {"": ["a", "b", 0]},
id="default_category is a 0",
),
pytest.param(
False,
- DataFrame({"": ["a", "b", False]}),
+ {"": ["a", "b", False]},
id="default_category is a bool",
),
pytest.param(
(1, 2),
- DataFrame({"": ["a", "b", (1, 2)]}),
+ {"": ["a", "b", (1, 2)]},
id="default_category is a tuple",
),
],
@@ -333,6 +333,7 @@ def test_no_prefix_string_cats_default_category(
):
dummies = DataFrame({"a": [1, 0, 0], "b": [0, 1, 0]})
result = from_dummies(dummies, default_category=default_category)
+ expected = DataFrame(expected)
if using_infer_string:
expected[""] = expected[""].astype("string[pyarrow_numpy]")
tm.assert_frame_equal(result, expected)
@@ -366,32 +367,32 @@ def test_with_prefix_contains_get_dummies_NaN_column():
[
pytest.param(
"x",
- DataFrame({"col1": ["a", "b", "x"], "col2": ["x", "a", "c"]}),
+ {"col1": ["a", "b", "x"], "col2": ["x", "a", "c"]},
id="default_category is a str",
),
pytest.param(
0,
- DataFrame({"col1": ["a", "b", 0], "col2": [0, "a", "c"]}),
+ {"col1": ["a", "b", 0], "col2": [0, "a", "c"]},
id="default_category is a 0",
),
pytest.param(
False,
- DataFrame({"col1": ["a", "b", False], "col2": [False, "a", "c"]}),
+ {"col1": ["a", "b", False], "col2": [False, "a", "c"]},
id="default_category is a False",
),
pytest.param(
{"col2": 1, "col1": 2.5},
- DataFrame({"col1": ["a", "b", 2.5], "col2": [1, "a", "c"]}),
+ {"col1": ["a", "b", 2.5], "col2": [1, "a", "c"]},
id="default_category is a dict with int and float values",
),
pytest.param(
{"col2": None, "col1": False},
- DataFrame({"col1": ["a", "b", False], "col2": [None, "a", "c"]}),
+ {"col1": ["a", "b", False], "col2": [None, "a", "c"]},
id="default_category is a dict with bool and None values",
),
pytest.param(
{"col2": (1, 2), "col1": [1.25, False]},
- DataFrame({"col1": ["a", "b", [1.25, False]], "col2": [(1, 2), "a", "c"]}),
+ {"col1": ["a", "b", [1.25, False]], "col2": [(1, 2), "a", "c"]},
id="default_category is a dict with list and tuple values",
),
],
@@ -402,6 +403,7 @@ def test_with_prefix_default_category(
result = from_dummies(
dummies_with_unassigned, sep="_", default_category=default_category
)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py
index 31260e4dcb7d2..082d5f0ee81ab 100644
--- a/pandas/tests/reshape/test_get_dummies.py
+++ b/pandas/tests/reshape/test_get_dummies.py
@@ -453,19 +453,19 @@ def test_dataframe_dummies_with_categorical(self, df, sparse, dtype):
[
(
{"data": DataFrame({"ä": ["a"]})},
- DataFrame({"ä_a": [True]}),
+ "ä_a",
),
(
{"data": DataFrame({"x": ["ä"]})},
- DataFrame({"x_ä": [True]}),
+ "x_ä",
),
(
{"data": DataFrame({"x": ["a"]}), "prefix": "ä"},
- DataFrame({"ä_a": [True]}),
+ "ä_a",
),
(
{"data": DataFrame({"x": ["a"]}), "prefix_sep": "ä"},
- DataFrame({"xäa": [True]}),
+ "xäa",
),
],
)
@@ -473,6 +473,7 @@ def test_dataframe_dummies_unicode(self, get_dummies_kwargs, expected):
# GH22084 get_dummies incorrectly encodes unicode characters
# in dataframe column names
result = get_dummies(**get_dummies_kwargs)
+ expected = DataFrame({expected: [True]})
tm.assert_frame_equal(result, expected)
def test_get_dummies_basic_drop_first(self, sparse):
diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py
index ff9f927597956..63367aee77f83 100644
--- a/pandas/tests/reshape/test_melt.py
+++ b/pandas/tests/reshape/test_melt.py
@@ -133,25 +133,21 @@ def test_vars_work_with_multiindex(self, df1):
["A"],
["B"],
0,
- DataFrame(
- {
- "A": {0: 1.067683, 1: -1.321405, 2: -0.807333},
- "CAP": {0: "B", 1: "B", 2: "B"},
- "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
- }
- ),
+ {
+ "A": {0: 1.067683, 1: -1.321405, 2: -0.807333},
+ "CAP": {0: "B", 1: "B", 2: "B"},
+ "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
+ },
),
(
["a"],
["b"],
1,
- DataFrame(
- {
- "a": {0: 1.067683, 1: -1.321405, 2: -0.807333},
- "low": {0: "b", 1: "b", 2: "b"},
- "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
- }
- ),
+ {
+ "a": {0: 1.067683, 1: -1.321405, 2: -0.807333},
+ "low": {0: "b", 1: "b", 2: "b"},
+ "value": {0: -1.110463, 1: 0.368915, 2: 0.08298},
+ },
),
],
)
@@ -159,6 +155,7 @@ def test_single_vars_work_with_multiindex(
self, id_vars, value_vars, col_level, expected, df1
):
result = df1.melt(id_vars, value_vars, col_level=col_level)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
@@ -287,13 +284,14 @@ def test_multiindex(self, df1):
@pytest.mark.parametrize(
"col",
[
- pd.Series(date_range("2010", periods=5, tz="US/Pacific")),
- pd.Series(["a", "b", "c", "a", "d"], dtype="category"),
- pd.Series([0, 1, 0, 0, 0]),
+ date_range("2010", periods=5, tz="US/Pacific"),
+ pd.Categorical(["a", "b", "c", "a", "d"]),
+ [0, 1, 0, 0, 0],
],
)
def test_pandas_dtypes(self, col):
# GH 15785
+ col = pd.Series(col)
df = DataFrame(
{"klass": range(5), "col": col, "attr1": [1, 0, 0, 0, 0], "attr2": col}
)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index af156a1da87f2..fbc3d2b8a7c35 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -744,18 +744,11 @@ def test_pivot_periods_with_margins(self):
result = df.pivot_table(index="a", columns="b", values="x", margins=True)
tm.assert_frame_equal(expected, result)
- @pytest.mark.parametrize(
- "values",
- [
- ["baz", "zoo"],
- np.array(["baz", "zoo"]),
- Series(["baz", "zoo"]),
- Index(["baz", "zoo"]),
- ],
- )
+ @pytest.mark.parametrize("box", [list, np.array, Series, Index])
@pytest.mark.parametrize("method", [True, False])
- def test_pivot_with_list_like_values(self, values, method):
+ def test_pivot_with_list_like_values(self, box, method):
# issue #17160
+ values = box(["baz", "zoo"])
df = DataFrame(
{
"foo": ["one", "one", "one", "two", "two", "two"],
diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py
index b5b19eef1106f..53af673e0f7b0 100644
--- a/pandas/tests/reshape/test_qcut.py
+++ b/pandas/tests/reshape/test_qcut.py
@@ -154,14 +154,15 @@ def test_qcut_wrong_length_labels(labels):
@pytest.mark.parametrize(
"labels, expected",
[
- (["a", "b", "c"], Categorical(["a", "b", "c"], ordered=True)),
- (list(range(3)), Categorical([0, 1, 2], ordered=True)),
+ (["a", "b", "c"], ["a", "b", "c"]),
+ (list(range(3)), [0, 1, 2]),
],
)
def test_qcut_list_like_labels(labels, expected):
# GH 13318
values = range(3)
result = qcut(values, 3, labels=labels)
+ expected = Categorical(expected, ordered=True)
tm.assert_categorical_equal(result, expected)
@@ -209,13 +210,14 @@ def test_single_quantile(data, start, end, length, labels):
@pytest.mark.parametrize(
"ser",
[
- Series(DatetimeIndex(["20180101", NaT, "20180103"])),
- Series(TimedeltaIndex(["0 days", NaT, "2 days"])),
+ DatetimeIndex(["20180101", NaT, "20180103"]),
+ TimedeltaIndex(["0 days", NaT, "2 days"]),
],
ids=lambda x: str(x.dtype),
)
def test_qcut_nat(ser, unit):
# see gh-19768
+ ser = Series(ser)
ser = ser.dt.as_unit(unit)
td = Timedelta(1, unit=unit).as_unit(unit)
diff --git a/pandas/tests/scalar/period/test_arithmetic.py b/pandas/tests/scalar/period/test_arithmetic.py
index 5dc0858de466c..97e486f9af060 100644
--- a/pandas/tests/scalar/period/test_arithmetic.py
+++ b/pandas/tests/scalar/period/test_arithmetic.py
@@ -476,10 +476,11 @@ def test_period_comparison_nat(self):
assert not left >= right
@pytest.mark.parametrize(
- "zerodim_arr, expected",
- ((np.array(0), False), (np.array(Period("2000-01", "M")), True)),
+ "scalar, expected",
+ ((0, False), (Period("2000-01", "M"), True)),
)
- def test_period_comparison_numpy_zerodim_arr(self, zerodim_arr, expected):
+ def test_period_comparison_numpy_zerodim_arr(self, scalar, expected):
+ zerodim_arr = np.array(scalar)
per = Period("2000-01", "M")
assert (per == zerodim_arr) is expected
diff --git a/pandas/tests/scalar/timedelta/methods/test_round.py b/pandas/tests/scalar/timedelta/methods/test_round.py
index 676b44a4d54f4..082c36999e06f 100644
--- a/pandas/tests/scalar/timedelta/methods/test_round.py
+++ b/pandas/tests/scalar/timedelta/methods/test_round.py
@@ -19,29 +19,31 @@ class TestTimedeltaRound:
# This first case has s1, s2 being the same as t1,t2 below
(
"ns",
- Timedelta("1 days 02:34:56.789123456"),
- Timedelta("-1 days 02:34:56.789123456"),
+ "1 days 02:34:56.789123456",
+ "-1 days 02:34:56.789123456",
),
(
"us",
- Timedelta("1 days 02:34:56.789123000"),
- Timedelta("-1 days 02:34:56.789123000"),
+ "1 days 02:34:56.789123000",
+ "-1 days 02:34:56.789123000",
),
(
"ms",
- Timedelta("1 days 02:34:56.789000000"),
- Timedelta("-1 days 02:34:56.789000000"),
+ "1 days 02:34:56.789000000",
+ "-1 days 02:34:56.789000000",
),
- ("s", Timedelta("1 days 02:34:57"), Timedelta("-1 days 02:34:57")),
- ("2s", Timedelta("1 days 02:34:56"), Timedelta("-1 days 02:34:56")),
- ("5s", Timedelta("1 days 02:34:55"), Timedelta("-1 days 02:34:55")),
- ("min", Timedelta("1 days 02:35:00"), Timedelta("-1 days 02:35:00")),
- ("12min", Timedelta("1 days 02:36:00"), Timedelta("-1 days 02:36:00")),
- ("h", Timedelta("1 days 03:00:00"), Timedelta("-1 days 03:00:00")),
- ("d", Timedelta("1 days"), Timedelta("-1 days")),
+ ("s", "1 days 02:34:57", "-1 days 02:34:57"),
+ ("2s", "1 days 02:34:56", "-1 days 02:34:56"),
+ ("5s", "1 days 02:34:55", "-1 days 02:34:55"),
+ ("min", "1 days 02:35:00", "-1 days 02:35:00"),
+ ("12min", "1 days 02:36:00", "-1 days 02:36:00"),
+ ("h", "1 days 03:00:00", "-1 days 03:00:00"),
+ ("d", "1 days", "-1 days"),
],
)
def test_round(self, freq, s1, s2):
+ s1 = Timedelta(s1)
+ s2 = Timedelta(s2)
t1 = Timedelta("1 days 02:34:56.789123456")
t2 = Timedelta("-1 days 02:34:56.789123456")
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index d2fa0f722ca6f..f3edaffdb315d 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -955,11 +955,12 @@ def test_rdivmod_invalid(self):
@pytest.mark.parametrize(
"arr",
[
- np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]),
- np.array([Timestamp("2021-11-09 09:54:00"), Timedelta("1D")]),
+ [Timestamp("20130101 9:01"), Timestamp("20121230 9:02")],
+ [Timestamp("2021-11-09 09:54:00"), Timedelta("1D")],
],
)
def test_td_op_timedelta_timedeltalike_array(self, op, arr):
+ arr = np.array(arr)
msg = "unsupported operand type|cannot use operands with types"
with pytest.raises(TypeError, match=msg):
op(arr, Timedelta("1D"))
diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py
index 4663f8cb71961..e680ca737b546 100644
--- a/pandas/tests/scalar/timedelta/test_constructors.py
+++ b/pandas/tests/scalar/timedelta/test_constructors.py
@@ -631,17 +631,16 @@ def test_timedelta_pass_td_and_kwargs_raises():
@pytest.mark.parametrize(
- "constructor, value, unit, expectation",
+ "constructor, value, unit",
[
- (Timedelta, "10s", "ms", (ValueError, "unit must not be specified")),
- (to_timedelta, "10s", "ms", (ValueError, "unit must not be specified")),
- (to_timedelta, ["1", 2, 3], "s", (ValueError, "unit must not be specified")),
+ (Timedelta, "10s", "ms"),
+ (to_timedelta, "10s", "ms"),
+ (to_timedelta, ["1", 2, 3], "s"),
],
)
-def test_string_with_unit(constructor, value, unit, expectation):
- exp, match = expectation
- with pytest.raises(exp, match=match):
- _ = constructor(value, unit=unit)
+def test_string_with_unit(constructor, value, unit):
+ with pytest.raises(ValueError, match="unit must not be specified"):
+ constructor(value, unit=unit)
@pytest.mark.parametrize(
diff --git a/pandas/tests/scalar/timestamp/methods/test_round.py b/pandas/tests/scalar/timestamp/methods/test_round.py
index 59c0fe8bbebfb..2fb0e1a8d3397 100644
--- a/pandas/tests/scalar/timestamp/methods/test_round.py
+++ b/pandas/tests/scalar/timestamp/methods/test_round.py
@@ -162,10 +162,6 @@ def test_floor(self, unit):
assert result._creso == dt._creso
@pytest.mark.parametrize("method", ["ceil", "round", "floor"])
- @pytest.mark.parametrize(
- "unit",
- ["ns", "us", "ms", "s"],
- )
def test_round_dst_border_ambiguous(self, method, unit):
# GH 18946 round near "fall back" DST
ts = Timestamp("2017-10-29 00:00:00", tz="UTC").tz_convert("Europe/Madrid")
@@ -197,10 +193,6 @@ def test_round_dst_border_ambiguous(self, method, unit):
["floor", "2018-03-11 03:01:00-0500", "2h"],
],
)
- @pytest.mark.parametrize(
- "unit",
- ["ns", "us", "ms", "s"],
- )
def test_round_dst_border_nonexistent(self, method, ts_str, freq, unit):
# GH 23324 round near "spring forward" DST
ts = Timestamp(ts_str, tz="America/Chicago").as_unit(unit)
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index f92e9145a2205..bbda9d3ee7dce 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -191,18 +191,17 @@ def test_timestamp_constructor_infer_fold_from_value(self, tz, ts_input, fold_ou
@pytest.mark.parametrize("tz", ["dateutil/Europe/London"])
@pytest.mark.parametrize(
- "ts_input,fold,value_out",
+ "fold,value_out",
[
- (datetime(2019, 10, 27, 1, 30, 0, 0), 0, 1572136200000000),
- (datetime(2019, 10, 27, 1, 30, 0, 0), 1, 1572139800000000),
+ (0, 1572136200000000),
+ (1, 1572139800000000),
],
)
- def test_timestamp_constructor_adjust_value_for_fold(
- self, tz, ts_input, fold, value_out
- ):
+ def test_timestamp_constructor_adjust_value_for_fold(self, tz, fold, value_out):
# Test for GH#25057
# Check that we adjust value for fold correctly
# based on timestamps since utc
+ ts_input = datetime(2019, 10, 27, 1, 30)
ts = Timestamp(ts_input, tz=tz, fold=fold)
result = ts._value
expected = value_out
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index fb844a3e43181..44a16e51f2c47 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -118,18 +118,16 @@ def test_is_end(self, end, tz):
assert getattr(ts, end)
# GH 12806
- @pytest.mark.parametrize(
- "data",
- [Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")],
- )
+ @pytest.mark.parametrize("tz", [None, "EST"])
# error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
"time_locale",
[None] + tm.get_locales(), # type: ignore[operator]
)
- def test_names(self, data, time_locale):
+ def test_names(self, tz, time_locale):
# GH 17354
# Test .day_name(), .month_name
+ data = Timestamp("2017-08-28 23:00:00", tz=tz)
if time_locale is None:
expected_day = "Monday"
expected_month = "August"
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 911f5d7b28e3f..2365ff62b1680 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -697,15 +697,16 @@ def test_dt_accessor_api(self):
assert isinstance(ser.dt, DatetimeProperties)
@pytest.mark.parametrize(
- "ser",
+ "data",
[
- Series(np.arange(5)),
- Series(list("abcde")),
- Series(np.random.default_rng(2).standard_normal(5)),
+ np.arange(5),
+ list("abcde"),
+ np.random.default_rng(2).standard_normal(5),
],
)
- def test_dt_accessor_invalid(self, ser):
+ def test_dt_accessor_invalid(self, data):
# GH#9322 check that series with incorrect dtypes don't have attr
+ ser = Series(data)
with pytest.raises(AttributeError, match="only use .dt accessor"):
ser.dt
assert not hasattr(ser, "dt")
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index 596a225c288b8..01c775e492888 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -561,14 +561,15 @@ def test_getitem_generator(string_series):
@pytest.mark.parametrize(
- "series",
+ "data",
[
- Series([0, 1]),
- Series(date_range("2012-01-01", periods=2)),
- Series(date_range("2012-01-01", periods=2, tz="CET")),
+ [0, 1],
+ date_range("2012-01-01", periods=2),
+ date_range("2012-01-01", periods=2, tz="CET"),
],
)
-def test_getitem_ndim_deprecated(series):
+def test_getitem_ndim_deprecated(data):
+ series = Series(data)
with pytest.raises(ValueError, match="Multi-dimensional indexing"):
series[:, None]
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index c52e47a812183..449b73ecf32fe 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -117,19 +117,21 @@ def test_getitem_setitem_ellipsis(using_copy_on_write, warn_copy_on_write):
"result_1, duplicate_item, expected_1",
[
[
- Series({1: 12, 2: [1, 2, 2, 3]}),
- Series({1: 313}),
+ {1: 12, 2: [1, 2, 2, 3]},
+ {1: 313},
Series({1: 12}, dtype=object),
],
[
- Series({1: [1, 2, 3], 2: [1, 2, 2, 3]}),
- Series({1: [1, 2, 3]}),
+ {1: [1, 2, 3], 2: [1, 2, 2, 3]},
+ {1: [1, 2, 3]},
Series({1: [1, 2, 3]}),
],
],
)
def test_getitem_with_duplicates_indices(result_1, duplicate_item, expected_1):
# GH 17610
+ result_1 = Series(result_1)
+ duplicate_item = Series(duplicate_item)
result = result_1._append(duplicate_item)
expected = expected_1._append(duplicate_item)
tm.assert_series_equal(result[1], expected)
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 23137f0975fb1..85ffb0f8fe647 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -1799,11 +1799,7 @@ def test_setitem_with_bool_indexer():
@pytest.mark.parametrize(
"item", [2.0, np.nan, np.finfo(float).max, np.finfo(float).min]
)
-# Test numpy arrays, lists and tuples as the input to be
-# broadcast
-@pytest.mark.parametrize(
- "box", [lambda x: np.array([x]), lambda x: [x], lambda x: (x,)]
-)
+@pytest.mark.parametrize("box", [np.array, list, tuple])
def test_setitem_bool_indexer_dont_broadcast_length1_values(size, mask, item, box):
# GH#44265
# see also tests.series.indexing.test_where.test_broadcast
@@ -1821,11 +1817,11 @@ def test_setitem_bool_indexer_dont_broadcast_length1_values(size, mask, item, bo
)
with pytest.raises(ValueError, match=msg):
# GH#44265
- ser[selection] = box(item)
+ ser[selection] = box([item])
else:
# In this corner case setting is equivalent to setting with the unboxed
# item
- ser[selection] = box(item)
+ ser[selection] = box([item])
expected = Series(np.arange(size, dtype=float))
expected[selection] = item
diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py
index c978481ca9988..e1139ea75f48b 100644
--- a/pandas/tests/series/indexing/test_where.py
+++ b/pandas/tests/series/indexing/test_where.py
@@ -297,11 +297,7 @@ def test_where_setitem_invalid():
@pytest.mark.parametrize(
"item", [2.0, np.nan, np.finfo(float).max, np.finfo(float).min]
)
-# Test numpy arrays, lists and tuples as the input to be
-# broadcast
-@pytest.mark.parametrize(
- "box", [lambda x: np.array([x]), lambda x: [x], lambda x: (x,)]
-)
+@pytest.mark.parametrize("box", [np.array, list, tuple])
def test_broadcast(size, mask, item, box):
# GH#8801, GH#4195
selection = np.resize(mask, size)
@@ -320,11 +316,11 @@ def test_broadcast(size, mask, item, box):
tm.assert_series_equal(s, expected)
s = Series(data)
- result = s.where(~selection, box(item))
+ result = s.where(~selection, box([item]))
tm.assert_series_equal(result, expected)
s = Series(data)
- result = s.mask(selection, box(item))
+ result = s.mask(selection, box([item]))
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 4d2cd2ba963fd..2588f195aab7e 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -164,14 +164,15 @@ def test_astype_empty_constructor_equality(self, dtype):
@pytest.mark.parametrize("dtype", [str, np.str_])
@pytest.mark.parametrize(
- "series",
+ "data",
[
- Series([string.digits * 10, rand_str(63), rand_str(64), rand_str(1000)]),
- Series([string.digits * 10, rand_str(63), rand_str(64), np.nan, 1.0]),
+ [string.digits * 10, rand_str(63), rand_str(64), rand_str(1000)],
+ [string.digits * 10, rand_str(63), rand_str(64), np.nan, 1.0],
],
)
- def test_astype_str_map(self, dtype, series, using_infer_string):
+ def test_astype_str_map(self, dtype, data, using_infer_string):
# see GH#4405
+ series = Series(data)
result = series.astype(dtype)
expected = series.map(str)
if using_infer_string:
@@ -459,13 +460,9 @@ def test_astype_nan_to_bool(self):
expected = Series(True, dtype="bool")
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize(
- "dtype",
- tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES,
- )
- def test_astype_ea_to_datetimetzdtype(self, dtype):
+ def test_astype_ea_to_datetimetzdtype(self, any_numeric_ea_dtype):
# GH37553
- ser = Series([4, 0, 9], dtype=dtype)
+ ser = Series([4, 0, 9], dtype=any_numeric_ea_dtype)
result = ser.astype(DatetimeTZDtype(tz="US/Pacific"))
expected = Series(
diff --git a/pandas/tests/series/methods/test_diff.py b/pandas/tests/series/methods/test_diff.py
index a46389087f87b..89c34aeb64206 100644
--- a/pandas/tests/series/methods/test_diff.py
+++ b/pandas/tests/series/methods/test_diff.py
@@ -74,13 +74,11 @@ def test_diff_dt64tz(self):
expected = Series(TimedeltaIndex(["NaT"] + ["1 days"] * 4), name="foo")
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize(
- "input,output,diff",
- [([False, True, True, False, False], [np.nan, True, False, True, False], 1)],
- )
- def test_diff_bool(self, input, output, diff):
+ def test_diff_bool(self):
# boolean series (test for fixing #17294)
- ser = Series(input)
+ data = [False, True, True, False, False]
+ output = [np.nan, True, False, True, False]
+ ser = Series(data)
result = ser.diff()
expected = Series(output)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_drop.py b/pandas/tests/series/methods/test_drop.py
index 5d9a469915cfb..d2a5a3324e886 100644
--- a/pandas/tests/series/methods/test_drop.py
+++ b/pandas/tests/series/methods/test_drop.py
@@ -31,17 +31,17 @@ def test_drop_unique_and_non_unique_index(
@pytest.mark.parametrize(
- "data, index, drop_labels, axis, error_type, error_desc",
+ "drop_labels, axis, error_type, error_desc",
[
# single string/tuple-like
- (range(3), list("abc"), "bc", 0, KeyError, "not found in axis"),
+ ("bc", 0, KeyError, "not found in axis"),
# bad axis
- (range(3), list("abc"), ("a",), 0, KeyError, "not found in axis"),
- (range(3), list("abc"), "one", "columns", ValueError, "No axis named columns"),
+ (("a",), 0, KeyError, "not found in axis"),
+ ("one", "columns", ValueError, "No axis named columns"),
],
)
-def test_drop_exception_raised(data, index, drop_labels, axis, error_type, error_desc):
- ser = Series(data, index=index)
+def test_drop_exception_raised(drop_labels, axis, error_type, error_desc):
+ ser = Series(range(3), index=list("abc"))
with pytest.raises(error_type, match=error_desc):
ser.drop(drop_labels, axis=axis)
diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py
index 10b2e98586365..31ef8ff896bcc 100644
--- a/pandas/tests/series/methods/test_drop_duplicates.py
+++ b/pandas/tests/series/methods/test_drop_duplicates.py
@@ -34,14 +34,14 @@ def test_drop_duplicates(any_numpy_dtype, keep, expected):
@pytest.mark.parametrize(
"keep, expected",
[
- ("first", Series([False, False, True, True])),
- ("last", Series([True, True, False, False])),
- (False, Series([True, True, True, True])),
+ ("first", [False, False, True, True]),
+ ("last", [True, True, False, False]),
+ (False, [True, True, True, True]),
],
)
def test_drop_duplicates_bool(keep, expected):
tc = Series([True, False, True, False])
-
+ expected = Series(expected)
tm.assert_series_equal(tc.duplicated(keep=keep), expected)
tm.assert_series_equal(tc.drop_duplicates(keep=keep), tc[~expected])
sc = tc.copy()
diff --git a/pandas/tests/series/methods/test_duplicated.py b/pandas/tests/series/methods/test_duplicated.py
index e177b5275d855..f5a387a7f302e 100644
--- a/pandas/tests/series/methods/test_duplicated.py
+++ b/pandas/tests/series/methods/test_duplicated.py
@@ -12,30 +12,32 @@
@pytest.mark.parametrize(
"keep, expected",
[
- ("first", Series([False, False, True, False, True], name="name")),
- ("last", Series([True, True, False, False, False], name="name")),
- (False, Series([True, True, True, False, True], name="name")),
+ ("first", [False, False, True, False, True]),
+ ("last", [True, True, False, False, False]),
+ (False, [True, True, True, False, True]),
],
)
def test_duplicated_keep(keep, expected):
ser = Series(["a", "b", "b", "c", "a"], name="name")
result = ser.duplicated(keep=keep)
+ expected = Series(expected, name="name")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"keep, expected",
[
- ("first", Series([False, False, True, False, True])),
- ("last", Series([True, True, False, False, False])),
- (False, Series([True, True, True, False, True])),
+ ("first", [False, False, True, False, True]),
+ ("last", [True, True, False, False, False]),
+ (False, [True, True, True, False, True]),
],
)
def test_duplicated_nan_none(keep, expected):
ser = Series([np.nan, 3, 3, None, np.nan], dtype=object)
result = ser.duplicated(keep=keep)
+ expected = Series(expected)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_explode.py b/pandas/tests/series/methods/test_explode.py
index 5a0188585ef30..15d615fc35081 100644
--- a/pandas/tests/series/methods/test_explode.py
+++ b/pandas/tests/series/methods/test_explode.py
@@ -74,11 +74,12 @@ def test_invert_array():
@pytest.mark.parametrize(
- "s", [pd.Series([1, 2, 3]), pd.Series(pd.date_range("2019", periods=3, tz="UTC"))]
+ "data", [[1, 2, 3], pd.date_range("2019", periods=3, tz="UTC")]
)
-def test_non_object_dtype(s):
- result = s.explode()
- tm.assert_series_equal(result, s)
+def test_non_object_dtype(data):
+ ser = pd.Series(data)
+ result = ser.explode()
+ tm.assert_series_equal(result, ser)
def test_typical_usecase():
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index f38e4a622cffa..a70d9f39ff488 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -786,13 +786,11 @@ def test_fillna_categorical(self, fill_value, expected_output):
@pytest.mark.parametrize(
"fill_value, expected_output",
[
- (Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]),
- (Series(["b", "d", "a", "d", "a"]), ["a", "d", "b", "d", "a"]),
+ (["a", "b", "c", "d", "e"], ["a", "b", "b", "d", "e"]),
+ (["b", "d", "a", "d", "a"], ["a", "d", "b", "d", "a"]),
(
- Series(
- Categorical(
- ["b", "d", "a", "d", "a"], categories=["b", "c", "d", "e", "a"]
- )
+ Categorical(
+ ["b", "d", "a", "d", "a"], categories=["b", "c", "d", "e", "a"]
),
["a", "d", "b", "d", "a"],
),
@@ -803,6 +801,7 @@ def test_fillna_categorical_with_new_categories(self, fill_value, expected_outpu
data = ["a", np.nan, "b", np.nan, np.nan]
ser = Series(Categorical(data, categories=["a", "b", "c", "d", "e"]))
exp = Series(Categorical(expected_output, categories=["a", "b", "c", "d", "e"]))
+ fill_value = Series(fill_value)
result = ser.fillna(fill_value)
tm.assert_series_equal(result, exp)
diff --git a/pandas/tests/series/methods/test_info.py b/pandas/tests/series/methods/test_info.py
index 29dd704f6efa9..bd1bc1781958c 100644
--- a/pandas/tests/series/methods/test_info.py
+++ b/pandas/tests/series/methods/test_info.py
@@ -141,19 +141,17 @@ def test_info_memory_usage_deep_pypy():
@pytest.mark.parametrize(
- "series, plus",
+ "index, plus",
[
- (Series(1, index=[1, 2, 3]), False),
- (Series(1, index=list("ABC")), True),
- (Series(1, index=MultiIndex.from_product([range(3), range(3)])), False),
- (
- Series(1, index=MultiIndex.from_product([range(3), ["foo", "bar"]])),
- True,
- ),
+ ([1, 2, 3], False),
+ (list("ABC"), True),
+ (MultiIndex.from_product([range(3), range(3)]), False),
+ (MultiIndex.from_product([range(3), ["foo", "bar"]]), True),
],
)
-def test_info_memory_usage_qualified(series, plus):
+def test_info_memory_usage_qualified(index, plus):
buf = StringIO()
+ series = Series(1, index=index)
series.info(buf=buf)
if plus:
assert "+" in buf.getvalue()
diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py
index f94f67b8cc40a..937b85a547bcd 100644
--- a/pandas/tests/series/methods/test_isin.py
+++ b/pandas/tests/series/methods/test_isin.py
@@ -211,18 +211,11 @@ def test_isin_large_series_mixed_dtypes_and_nan(monkeypatch):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize(
- "array,expected",
- [
- (
- [0, 1j, 1j, 1, 1 + 1j, 1 + 2j, 1 + 1j],
- Series([False, True, True, False, True, True, True], dtype=bool),
- )
- ],
-)
-def test_isin_complex_numbers(array, expected):
+def test_isin_complex_numbers():
# GH 17927
+ array = [0, 1j, 1j, 1, 1 + 1j, 1 + 2j, 1 + 1j]
result = Series(array).isin([1j, 1 + 1j, 1 + 2j])
+ expected = Series([False, True, True, False, True, True, True], dtype=bool)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index b0f4e233ba5eb..5266bbf7741d7 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -395,13 +395,13 @@ def test_replace_mixed_types_with_string(self):
@pytest.mark.parametrize(
"categorical, numeric",
[
- (pd.Categorical(["A"], categories=["A", "B"]), [1]),
- (pd.Categorical(["A", "B"], categories=["A", "B"]), [1, 2]),
+ (["A"], [1]),
+ (["A", "B"], [1, 2]),
],
)
def test_replace_categorical(self, categorical, numeric):
# GH 24971, GH#23305
- ser = pd.Series(categorical)
+ ser = pd.Series(pd.Categorical(categorical, categories=["A", "B"]))
msg = "Downcasting behavior in `replace`"
msg = "with CategoricalDtype is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index 3f18ae6c13880..191aa36ad5d41 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -76,21 +76,23 @@ def test_update_dtypes(self, other, dtype, expected, warn):
tm.assert_series_equal(ser, expected)
@pytest.mark.parametrize(
- "series, other, expected",
+ "values, other, expected",
[
# update by key
(
- Series({"a": 1, "b": 2, "c": 3, "d": 4}),
+ {"a": 1, "b": 2, "c": 3, "d": 4},
{"b": 5, "c": np.nan},
- Series({"a": 1, "b": 5, "c": 3, "d": 4}),
+ {"a": 1, "b": 5, "c": 3, "d": 4},
),
# update by position
- (Series([1, 2, 3, 4]), [np.nan, 5, 1], Series([1, 5, 1, 4])),
+ ([1, 2, 3, 4], [np.nan, 5, 1], [1, 5, 1, 4]),
],
)
- def test_update_from_non_series(self, series, other, expected):
+ def test_update_from_non_series(self, values, other, expected):
# GH 33215
+ series = Series(values)
series.update(other)
+ expected = Series(expected)
tm.assert_series_equal(series, expected)
@pytest.mark.parametrize(
diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py
index 859010d9c79c6..7f882fa348b7e 100644
--- a/pandas/tests/series/methods/test_value_counts.py
+++ b/pandas/tests/series/methods/test_value_counts.py
@@ -225,30 +225,14 @@ def test_value_counts_bool_with_nan(self, ser, dropna, exp):
out = ser.value_counts(dropna=dropna)
tm.assert_series_equal(out, exp)
- @pytest.mark.parametrize(
- "input_array,expected",
- [
- (
- [1 + 1j, 1 + 1j, 1, 3j, 3j, 3j],
- Series(
- [3, 2, 1],
- index=Index([3j, 1 + 1j, 1], dtype=np.complex128),
- name="count",
- ),
- ),
- (
- np.array([1 + 1j, 1 + 1j, 1, 3j, 3j, 3j], dtype=np.complex64),
- Series(
- [3, 2, 1],
- index=Index([3j, 1 + 1j, 1], dtype=np.complex64),
- name="count",
- ),
- ),
- ],
- )
- def test_value_counts_complex_numbers(self, input_array, expected):
+ @pytest.mark.parametrize("dtype", [np.complex128, np.complex64])
+ def test_value_counts_complex_numbers(self, dtype):
# GH 17927
+ input_array = np.array([1 + 1j, 1 + 1j, 1, 3j, 3j, 3j], dtype=dtype)
result = Series(input_array).value_counts()
+ expected = Series(
+ [3, 2, 1], index=Index([3j, 1 + 1j, 1], dtype=dtype), name="count"
+ )
tm.assert_series_equal(result, expected)
def test_value_counts_masked(self):
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index b40e2e99dae2e..d71a515c85bd0 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -674,22 +674,12 @@ def test_ne(self):
tm.assert_numpy_array_equal(ts.index != 5, expected)
tm.assert_numpy_array_equal(~(ts.index == 5), expected)
- @pytest.mark.parametrize(
- "left, right",
- [
- (
- Series([1, 2, 3], index=list("ABC"), name="x"),
- Series([2, 2, 2], index=list("ABD"), name="x"),
- ),
- (
- Series([1, 2, 3], index=list("ABC"), name="x"),
- Series([2, 2, 2, 2], index=list("ABCD"), name="x"),
- ),
- ],
- )
- def test_comp_ops_df_compat(self, left, right, frame_or_series):
+ @pytest.mark.parametrize("right_data", [[2, 2, 2], [2, 2, 2, 2]])
+ def test_comp_ops_df_compat(self, right_data, frame_or_series):
# GH 1134
# GH 50083 to clarify that index and columns must be identically labeled
+ left = Series([1, 2, 3], index=list("ABC"), name="x")
+ right = Series(right_data, index=list("ABDC")[: len(right_data)], name="x")
if frame_or_series is not Series:
msg = (
rf"Can only compare identically-labeled \(both index and columns\) "
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index b802e92e4fcca..55ca1f98f6d6c 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -335,11 +335,11 @@ def test_constructor_index_dtype(self, dtype):
@pytest.mark.parametrize(
"input_vals",
[
- ([1, 2]),
- (["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"))),
- ([Interval(left=0, right=5)]),
+ [1, 2],
+ ["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")),
+ [Interval(left=0, right=5)],
],
)
def test_constructor_list_str(self, input_vals, string_dtype):
@@ -1806,15 +1806,10 @@ def test_constructor_datetimelike_scalar_to_string_dtype(
expected = Series(["M", "M", "M"], index=[1, 2, 3], dtype=nullable_string_dtype)
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize(
- "values",
- [
- [np.datetime64("2012-01-01"), np.datetime64("2013-01-01")],
- ["2012-01-01", "2013-01-01"],
- ],
- )
- def test_constructor_sparse_datetime64(self, values):
+ @pytest.mark.parametrize("box", [lambda x: x, np.datetime64])
+ def test_constructor_sparse_datetime64(self, box):
# https://github.com/pandas-dev/pandas/issues/35762
+ values = [box("2012-01-01"), box("2013-01-01")]
dtype = pd.SparseDtype("datetime64[ns]")
result = Series(values, dtype=dtype)
arr = pd.arrays.SparseArray(values, dtype=dtype)
diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py
index e6f7b2a5e69e0..68d7fd8b90df2 100644
--- a/pandas/tests/series/test_cumulative.py
+++ b/pandas/tests/series/test_cumulative.py
@@ -94,8 +94,8 @@ def test_cummin_cummax_datetimelike(self, ts, method, skipna, exp_tdi):
@pytest.mark.parametrize(
"func, exp",
[
- ("cummin", pd.Period("2012-1-1", freq="D")),
- ("cummax", pd.Period("2012-1-2", freq="D")),
+ ("cummin", "2012-1-1"),
+ ("cummax", "2012-1-2"),
],
)
def test_cummin_cummax_period(self, func, exp):
@@ -108,6 +108,7 @@ def test_cummin_cummax_period(self, func, exp):
tm.assert_series_equal(result, expected)
result = getattr(ser, func)(skipna=True)
+ exp = pd.Period(exp, freq="D")
expected = pd.Series([pd.Period("2012-1-1", freq="D"), pd.NaT, exp])
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py
index d9c94e871bd4b..755d26623cf98 100644
--- a/pandas/tests/series/test_logical_ops.py
+++ b/pandas/tests/series/test_logical_ops.py
@@ -345,9 +345,9 @@ def test_reversed_logical_op_with_index_returns_series(self, op):
@pytest.mark.parametrize(
"op, expected",
[
- (ops.rand_, Series([False, False])),
- (ops.ror_, Series([True, True])),
- (ops.rxor, Series([True, True])),
+ (ops.rand_, [False, False]),
+ (ops.ror_, [True, True]),
+ (ops.rxor, [True, True]),
],
)
def test_reverse_ops_with_index(self, op, expected):
@@ -358,6 +358,7 @@ def test_reverse_ops_with_index(self, op, expected):
idx = Index([False, True])
result = op(ser, idx)
+ expected = Series(expected)
tm.assert_series_equal(result, expected)
def test_logical_ops_label_based(self, using_infer_string):
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56745 | 2024-01-05T18:18:48Z | 2024-01-10T21:51:18Z | 2024-01-10T21:51:18Z | 2024-01-10T21:51:21Z |
Backport PR #56677 on branch 2.2.x (Fix integral truediv and floordiv for pyarrow types with large divisor and avoid floating points for floordiv) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 4222de8ce324f..0b04a1d313a6d 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -786,6 +786,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` and :meth:`Series.__truediv__` for :class:`ArrowDtype` with integral dtypes raising for large divisors (:issue:`56706`)
- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 0bc01d2da330a..3858ce4cf0ea1 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -109,30 +109,50 @@
def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
- ) -> pa.ChunkedArray:
+ ) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
+ # GH: 56645.
# https://github.com/apache/arrow/issues/35563
- # Arrow does not allow safe casting large integral values to float64.
- # Intentionally not using arrow_array.cast because it could be a scalar
- # value in reflected case, and safe=False only added to
- # scalar cast in pyarrow 13.
- return pc.cast(arrow_array, pa.float64(), safe=False)
- return arrow_array
+ return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast(
+ pa_object, pa.float64(), safe=False
+ )
+
+ return arrow_array, pa_object
def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
right: pa.ChunkedArray | pa.Array | pa.Scalar,
) -> pa.ChunkedArray:
- # Ensure int // int -> int mirroring Python/Numpy behavior
- # as pc.floor(pc.divide_checked(int, int)) -> float
- converted_left = cast_for_truediv(left, right)
- result = pc.floor(pc.divide(converted_left, right))
+ # TODO: Replace with pyarrow floordiv kernel.
+ # https://github.com/apache/arrow/issues/39386
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
+ divided = pc.divide_checked(left, right)
+ if pa.types.is_signed_integer(divided.type):
+ # GH 56676
+ has_remainder = pc.not_equal(pc.multiply(divided, right), left)
+ has_one_negative_operand = pc.less(
+ pc.bit_wise_xor(left, right),
+ pa.scalar(0, type=divided.type),
+ )
+ result = pc.if_else(
+ pc.and_(
+ has_remainder,
+ has_one_negative_operand,
+ ),
+ # GH: 55561
+ pc.subtract(divided, pa.scalar(1, type=divided.type)),
+ divided,
+ )
+ else:
+ result = divided
result = result.cast(left.type)
+ else:
+ divided = pc.divide(left, right)
+ result = pc.floor(divided)
return result
ARROW_ARITHMETIC_FUNCS = {
@@ -142,8 +162,8 @@ def floordiv_compat(
"rsub": lambda x, y: pc.subtract_checked(y, x),
"mul": pc.multiply_checked,
"rmul": lambda x, y: pc.multiply_checked(y, x),
- "truediv": lambda x, y: pc.divide(cast_for_truediv(x, y), y),
- "rtruediv": lambda x, y: pc.divide(y, cast_for_truediv(x, y)),
+ "truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)),
+ "rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 6689fb34f2ae3..05a112e464677 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3260,13 +3260,82 @@ def test_arrow_floordiv():
def test_arrow_floordiv_large_values():
- # GH 55561
+ # GH 56645
a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
expected = pd.Series([1425801600000], dtype="int64[pyarrow]")
result = a // 1_000_000
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_floordiv_large_integral_result(dtype):
+ # GH 56676
+ a = pd.Series([18014398509481983], dtype=dtype)
+ result = a // 1
+ tm.assert_series_equal(result, a)
+
+
+@pytest.mark.parametrize("pa_type", tm.SIGNED_INT_PYARROW_DTYPES)
+def test_arrow_floordiv_larger_divisor(pa_type):
+ # GH 56676
+ dtype = ArrowDtype(pa_type)
+ a = pd.Series([-23], dtype=dtype)
+ result = a // 24
+ expected = pd.Series([-1], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.SIGNED_INT_PYARROW_DTYPES)
+def test_arrow_floordiv_integral_invalid(pa_type):
+ # GH 56676
+ min_value = np.iinfo(pa_type.to_pandas_dtype()).min
+ a = pd.Series([min_value], dtype=ArrowDtype(pa_type))
+ with pytest.raises(pa.lib.ArrowInvalid, match="overflow|not in range"):
+ a // -1
+ with pytest.raises(pa.lib.ArrowInvalid, match="divide by zero"):
+ a // 0
+
+
+@pytest.mark.parametrize("dtype", tm.FLOAT_PYARROW_DTYPES_STR_REPR)
+def test_arrow_floordiv_floating_0_divisor(dtype):
+ # GH 56676
+ a = pd.Series([2], dtype=dtype)
+ result = a // 0
+ expected = pd.Series([float("inf")], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES)
+def test_arrow_integral_floordiv_large_values(pa_type):
+ # GH 56676
+ max_value = np.iinfo(pa_type.to_pandas_dtype()).max
+ dtype = ArrowDtype(pa_type)
+ a = pd.Series([max_value], dtype=dtype)
+ b = pd.Series([1], dtype=dtype)
+ result = a // b
+ tm.assert_series_equal(result, a)
+
+
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_true_division_large_divisor(dtype):
+ # GH 56706
+ a = pd.Series([0], dtype=dtype)
+ b = pd.Series([18014398509481983], dtype=dtype)
+ expected = pd.Series([0], dtype="float64[pyarrow]")
+ result = a / b
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_floor_division_large_divisor(dtype):
+ # GH 56706
+ a = pd.Series([0], dtype=dtype)
+ b = pd.Series([18014398509481983], dtype=dtype)
+ expected = pd.Series([0], dtype=dtype)
+ result = a // b
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| Backport PR #56677: Fix integral truediv and floordiv for pyarrow types with large divisor and avoid floating points for floordiv | https://api.github.com/repos/pandas-dev/pandas/pulls/56744 | 2024-01-05T18:09:24Z | 2024-01-05T18:56:14Z | 2024-01-05T18:56:14Z | 2024-01-05T18:56:14Z |
DOC: Modified docstring of DataFrame.to_dict() to make the usage of orient='records' more clear | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6851955d693bc..8db437ccec389 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2066,7 +2066,9 @@ def to_dict(
index : bool, default True
Whether to include the index item (and index_names item if `orient`
is 'tight') in the returned dictionary. Can only be ``False``
- when `orient` is 'split' or 'tight'.
+ when `orient` is 'split' or 'tight'. Note that when `orient` is
+ 'records', this parameter does not take effect (index item always
+ not included).
.. versionadded:: 2.0.0
| Modified documentation for parameter `index` as is mentioned in #56483.
However, I don't think this should be the final solution to this issue. The current behavior remains counter-intuitive and will confuse users who haven't checked the doc.
closes #56483 | https://api.github.com/repos/pandas-dev/pandas/pulls/56743 | 2024-01-05T12:24:58Z | 2024-01-05T18:03:29Z | 2024-01-05T18:03:29Z | 2024-01-05T18:03:36Z |
ENH: enable server side cursors when chunksize is set | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 9024961688c6b..5a5702bf36587 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1636,6 +1636,8 @@ def run_transaction(self):
def execute(self, sql: str | Select | TextClause, params=None):
"""Simple passthrough to SQLAlchemy connectable"""
args = [] if params is None else [params]
+ if self.returns_generator:
+ self.con.execution_options(stream_results=True)
if isinstance(sql, str):
return self.con.exec_driver_sql(sql, *args)
return self.con.execute(sql, *args)
@@ -1814,11 +1816,11 @@ def read_query(
read_sql
"""
+ self.returns_generator = chunksize is not None
result = self.execute(sql, params)
columns = result.keys()
if chunksize is not None:
- self.returns_generator = True
return self._query_iterator(
result,
self.exit_stack,
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index c8f4d68230e5b..fb900a033f6f5 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1189,6 +1189,24 @@ def test_read_iris_table_chunksize(conn, request):
check_iris_frame(iris_frame)
+@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris)
+def test_sqlalchemy_read_table_chunksize_stream_results(conn, request):
+ conn = request.getfixturevalue(conn)
+ with sql.SQLDatabase(conn) as pandasSQL:
+ assert list(pandasSQL.read_table("iris", chunksize=10000))
+ execution_options = pandasSQL.con.get_execution_options()
+ assert execution_options["stream_results"] is True
+
+
+@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris)
+def test_sqlalchemy_read_sql_chunksize_stream_results(conn, request):
+ conn = request.getfixturevalue(conn)
+ with sql.SQLDatabase(conn) as pandasSQL:
+ assert list(pandasSQL.read_sql("SELECT * FROM iris", chunksize=10000))
+ execution_options = pandasSQL.con.get_execution_options()
+ assert execution_options["stream_results"] is True
+
+
@pytest.mark.parametrize("conn", sqlalchemy_connectable)
def test_to_sql_callable(conn, test_frame1, request):
conn = request.getfixturevalue(conn)
| Please look at the previous attempts in #40796 and #46166. A lot of changes have happened since that PR. Since `SQLTable` (or `PandasSQL`) seems polymorphic, I did not want to change the function signature of `execute()` and noticed the use of `self.returns_generator` which can be used to use server-side cursors or not.
- [x] closes #35689
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56742 | 2024-01-05T11:37:47Z | 2024-02-28T17:51:21Z | null | 2024-02-29T09:09:38Z |
TYP: mostly DataFrame return overloads | diff --git a/pandas/core/base.py b/pandas/core/base.py
index a1484d9ad032b..492986faba4d3 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -8,6 +8,7 @@
from typing import (
TYPE_CHECKING,
Any,
+ Callable,
Generic,
Literal,
cast,
@@ -106,7 +107,7 @@ class PandasObject(DirNamesMixin):
_cache: dict[str, Any]
@property
- def _constructor(self):
+ def _constructor(self) -> Callable[..., Self]:
"""
Class constructor (for this class it's just `__class__`).
"""
@@ -802,7 +803,7 @@ def argmin(
# "int")
return result # type: ignore[return-value]
- def tolist(self):
+ def tolist(self) -> list:
"""
Return a list of the values.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index e48e5d9023f33..3cce697120cd2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -10674,7 +10674,7 @@ def round(
"""
from pandas.core.reshape.concat import concat
- def _dict_round(df: DataFrame, decimals):
+ def _dict_round(df: DataFrame, decimals) -> Iterator[Series]:
for col, vals in df.items():
try:
yield _series_round(vals, decimals[col])
@@ -11110,7 +11110,7 @@ def c(x):
# ----------------------------------------------------------------------
# ndarray-like stats methods
- def count(self, axis: Axis = 0, numeric_only: bool = False):
+ def count(self, axis: Axis = 0, numeric_only: bool = False) -> Series:
"""
Count non-NA cells for each column or row.
@@ -11356,9 +11356,42 @@ def _reduce_axis1(self, name: str, func, skipna: bool) -> Series:
res_ser = self._constructor_sliced(result, index=self.index, copy=False)
return res_ser
- @doc(make_doc("any", ndim=2))
# error: Signature of "any" incompatible with supertype "NDFrame"
- def any( # type: ignore[override]
+ @overload # type: ignore[override]
+ def any(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def any(
+ self,
+ *,
+ axis: None,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> bool:
+ ...
+
+ @overload
+ def any(
+ self,
+ *,
+ axis: Axis | None,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> Series | bool:
+ ...
+
+ @doc(make_doc("any", ndim=2))
+ def any(
self,
*,
axis: Axis | None = 0,
@@ -11373,6 +11406,39 @@ def any( # type: ignore[override]
result = result.__finalize__(self, method="any")
return result
+ @overload
+ def all(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def all(
+ self,
+ *,
+ axis: None,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> bool:
+ ...
+
+ @overload
+ def all(
+ self,
+ *,
+ axis: Axis | None,
+ bool_only: bool = ...,
+ skipna: bool = ...,
+ **kwargs,
+ ) -> Series | bool:
+ ...
+
@doc(make_doc("all", ndim=2))
def all(
self,
@@ -11388,6 +11454,40 @@ def all(
result = result.__finalize__(self, method="all")
return result
+ # error: Signature of "min" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def min(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def min(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def min(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("min", ndim=2))
def min(
self,
@@ -11395,12 +11495,48 @@ def min(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().min(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().min(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="min")
return result
+ # error: Signature of "max" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def max(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def max(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def max(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("max", ndim=2))
def max(
self,
@@ -11408,8 +11544,10 @@ def max(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().max(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().max(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="max")
return result
@@ -11422,8 +11560,14 @@ def sum(
numeric_only: bool = False,
min_count: int = 0,
**kwargs,
- ):
- result = super().sum(axis, skipna, numeric_only, min_count, **kwargs)
+ ) -> Series:
+ result = super().sum(
+ axis=axis,
+ skipna=skipna,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ **kwargs,
+ )
return result.__finalize__(self, method="sum")
@doc(make_doc("prod", ndim=2))
@@ -11434,10 +11578,50 @@ def prod(
numeric_only: bool = False,
min_count: int = 0,
**kwargs,
- ):
- result = super().prod(axis, skipna, numeric_only, min_count, **kwargs)
+ ) -> Series:
+ result = super().prod(
+ axis=axis,
+ skipna=skipna,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ **kwargs,
+ )
return result.__finalize__(self, method="prod")
+ # error: Signature of "mean" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def mean(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def mean(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def mean(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("mean", ndim=2))
def mean(
self,
@@ -11445,12 +11629,48 @@ def mean(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().mean(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().mean(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="mean")
return result
+ # error: Signature of "median" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def median(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def median(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def median(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("median", ndim=2))
def median(
self,
@@ -11458,12 +11678,51 @@ def median(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().median(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().median(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="median")
return result
+ # error: Signature of "sem" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def sem(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def sem(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def sem(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("sem", ndim=2))
def sem(
self,
@@ -11472,12 +11731,51 @@ def sem(
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().sem(axis, skipna, ddof, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().sem(
+ axis=axis, skipna=skipna, ddof=ddof, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="sem")
return result
+ # error: Signature of "var" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def var(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def var(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def var(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("var", ndim=2))
def var(
self,
@@ -11486,12 +11784,51 @@ def var(
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().var(axis, skipna, ddof, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().var(
+ axis=axis, skipna=skipna, ddof=ddof, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="var")
return result
+ # error: Signature of "std" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def std(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def std(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def std(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ ddof: int = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("std", ndim=2))
def std(
self,
@@ -11500,12 +11837,48 @@ def std(
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().std(axis, skipna, ddof, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().std(
+ axis=axis, skipna=skipna, ddof=ddof, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="std")
return result
+ # error: Signature of "skew" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def skew(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def skew(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def skew(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("skew", ndim=2))
def skew(
self,
@@ -11513,12 +11886,48 @@ def skew(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().skew(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().skew(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="skew")
return result
+ # error: Signature of "kurt" incompatible with supertype "NDFrame"
+ @overload # type: ignore[override]
+ def kurt(
+ self,
+ *,
+ axis: Axis = ...,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def kurt(
+ self,
+ *,
+ axis: None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Any:
+ ...
+
+ @overload
+ def kurt(
+ self,
+ *,
+ axis: Axis | None,
+ skipna: bool = ...,
+ numeric_only: bool = ...,
+ **kwargs,
+ ) -> Series | Any:
+ ...
+
@doc(make_doc("kurt", ndim=2))
def kurt(
self,
@@ -11526,13 +11935,16 @@ def kurt(
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
- ):
- result = super().kurt(axis, skipna, numeric_only, **kwargs)
+ ) -> Series | Any:
+ result = super().kurt(
+ axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
if isinstance(result, Series):
result = result.__finalize__(self, method="kurt")
return result
- kurtosis = kurt
+ # error: Incompatible types in assignment
+ kurtosis = kurt # type: ignore[assignment]
product = prod
@doc(make_doc("cummin", ndim=2))
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3c71784ad81c4..f458e058c9755 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -11805,6 +11805,7 @@ def _logical_func(
def any(
self,
+ *,
axis: Axis | None = 0,
bool_only: bool_t = False,
skipna: bool_t = True,
@@ -11816,6 +11817,7 @@ def any(
def all(
self,
+ *,
axis: Axis = 0,
bool_only: bool_t = False,
skipna: bool_t = True,
@@ -11919,6 +11921,7 @@ def _stat_function_ddof(
def sem(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
ddof: int = 1,
@@ -11931,6 +11934,7 @@ def sem(
def var(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
ddof: int = 1,
@@ -11943,6 +11947,7 @@ def var(
def std(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
ddof: int = 1,
@@ -11974,6 +11979,7 @@ def _stat_function(
def min(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -11990,6 +11996,7 @@ def min(
def max(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12006,6 +12013,7 @@ def max(
def mean(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12017,6 +12025,7 @@ def mean(
def median(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12028,6 +12037,7 @@ def median(
def skew(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12039,6 +12049,7 @@ def skew(
def kurt(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12091,6 +12102,7 @@ def _min_count_stat_function(
def sum(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
@@ -12103,6 +12115,7 @@ def sum(
def prod(
self,
+ *,
axis: Axis | None = 0,
skipna: bool_t = True,
numeric_only: bool_t = False,
diff --git a/pandas/core/reshape/encoding.py b/pandas/core/reshape/encoding.py
index fae5c082c72a0..fef32fca828a9 100644
--- a/pandas/core/reshape/encoding.py
+++ b/pandas/core/reshape/encoding.py
@@ -6,10 +6,7 @@
Iterable,
)
import itertools
-from typing import (
- TYPE_CHECKING,
- cast,
-)
+from typing import TYPE_CHECKING
import numpy as np
@@ -492,7 +489,7 @@ def from_dummies(
f"Received 'data' of type: {type(data).__name__}"
)
- col_isna_mask = cast(Series, data.isna().any())
+ col_isna_mask = data.isna().any()
if col_isna_mask.any():
raise ValueError(
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 641a44efbf286..8093f9aa70cba 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -6435,7 +6435,9 @@ def min(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.min(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.min(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
@doc(make_doc("max", ndim=1))
def max(
@@ -6445,7 +6447,9 @@ def max(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.max(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.max(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
@doc(make_doc("sum", ndim=1))
def sum(
@@ -6456,7 +6460,14 @@ def sum(
min_count: int = 0,
**kwargs,
):
- return NDFrame.sum(self, axis, skipna, numeric_only, min_count, **kwargs)
+ return NDFrame.sum(
+ self,
+ axis=axis,
+ skipna=skipna,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ **kwargs,
+ )
@doc(make_doc("prod", ndim=1))
def prod(
@@ -6467,7 +6478,14 @@ def prod(
min_count: int = 0,
**kwargs,
):
- return NDFrame.prod(self, axis, skipna, numeric_only, min_count, **kwargs)
+ return NDFrame.prod(
+ self,
+ axis=axis,
+ skipna=skipna,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ **kwargs,
+ )
@doc(make_doc("mean", ndim=1))
def mean(
@@ -6477,7 +6495,9 @@ def mean(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.mean(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.mean(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
@doc(make_doc("median", ndim=1))
def median(
@@ -6487,7 +6507,9 @@ def median(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.median(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.median(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
@doc(make_doc("sem", ndim=1))
def sem(
@@ -6498,7 +6520,14 @@ def sem(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.sem(self, axis, skipna, ddof, numeric_only, **kwargs)
+ return NDFrame.sem(
+ self,
+ axis=axis,
+ skipna=skipna,
+ ddof=ddof,
+ numeric_only=numeric_only,
+ **kwargs,
+ )
@doc(make_doc("var", ndim=1))
def var(
@@ -6509,7 +6538,14 @@ def var(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.var(self, axis, skipna, ddof, numeric_only, **kwargs)
+ return NDFrame.var(
+ self,
+ axis=axis,
+ skipna=skipna,
+ ddof=ddof,
+ numeric_only=numeric_only,
+ **kwargs,
+ )
@doc(make_doc("std", ndim=1))
def std(
@@ -6520,7 +6556,14 @@ def std(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.std(self, axis, skipna, ddof, numeric_only, **kwargs)
+ return NDFrame.std(
+ self,
+ axis=axis,
+ skipna=skipna,
+ ddof=ddof,
+ numeric_only=numeric_only,
+ **kwargs,
+ )
@doc(make_doc("skew", ndim=1))
def skew(
@@ -6530,7 +6573,9 @@ def skew(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.skew(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.skew(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
@doc(make_doc("kurt", ndim=1))
def kurt(
@@ -6540,7 +6585,9 @@ def kurt(
numeric_only: bool = False,
**kwargs,
):
- return NDFrame.kurt(self, axis, skipna, numeric_only, **kwargs)
+ return NDFrame.kurt(
+ self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs
+ )
kurtosis = kurt
product = prod
| - `DataFrame.any/bool` return `bool` when `axis=None` and `Series` otherwise
- `DataFrame.sum/prod` currently always returns a `Series` (but will return anything when `axis=None` in the future)
- `DataFrame.mean/median/var/std/skew/kurt` return `Series` when `axis` is not `None` and potentially anything when `axis=None`
I assume it is fine to directly use keyword-only arguments in NDFrame as it is private(?), and Series+DataFrame overwrite the methods in question. | https://api.github.com/repos/pandas-dev/pandas/pulls/56739 | 2024-01-05T01:56:12Z | 2024-02-13T01:22:05Z | 2024-02-13T01:22:05Z | 2024-04-07T10:59:30Z |
TST/CLN: Test parametrizations 2 | diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py
index 3ef3f3ad4d3a2..49c6a91236db7 100644
--- a/pandas/tests/indexes/base_class/test_setops.py
+++ b/pandas/tests/indexes/base_class/test_setops.py
@@ -149,13 +149,13 @@ def test_intersection_str_dates(self, sort):
@pytest.mark.parametrize(
"index2,expected_arr",
- [(Index(["B", "D"]), ["B"]), (Index(["B", "D", "A"]), ["A", "B"])],
+ [(["B", "D"], ["B"]), (["B", "D", "A"], ["A", "B"])],
)
def test_intersection_non_monotonic_non_unique(self, index2, expected_arr, sort):
# non-monotonic non-unique
index1 = Index(["A", "B", "A", "C"])
expected = Index(expected_arr)
- result = index1.intersection(index2, sort=sort)
+ result = index1.intersection(Index(index2), sort=sort)
if sort is None:
expected = expected.sort_values()
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index 019d434680661..024f37ee5b710 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -526,17 +526,13 @@ def test_range_tz_pytz(self):
@pytest.mark.parametrize(
"start, end",
[
- [
- Timestamp(datetime(2014, 3, 6), tz="US/Eastern"),
- Timestamp(datetime(2014, 3, 12), tz="US/Eastern"),
- ],
- [
- Timestamp(datetime(2013, 11, 1), tz="US/Eastern"),
- Timestamp(datetime(2013, 11, 6), tz="US/Eastern"),
- ],
+ [datetime(2014, 3, 6), datetime(2014, 3, 12)],
+ [datetime(2013, 11, 1), datetime(2013, 11, 6)],
],
)
def test_range_tz_dst_straddle_pytz(self, start, end):
+ start = Timestamp(start, tz="US/Eastern")
+ end = Timestamp(end, tz="US/Eastern")
dr = date_range(start, end, freq="D")
assert dr[0] == start
assert dr[-1] == end
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 7391d39bdde7b..006a06e529971 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -789,23 +789,20 @@ def test_is_overlapping(self, start, shift, na_value, closed):
@pytest.mark.parametrize(
"tuples",
[
- list(zip(range(10), range(1, 11))),
- list(
- zip(
- date_range("20170101", periods=10),
- date_range("20170101", periods=10),
- )
+ zip(range(10), range(1, 11)),
+ zip(
+ date_range("20170101", periods=10),
+ date_range("20170101", periods=10),
),
- list(
- zip(
- timedelta_range("0 days", periods=10),
- timedelta_range("1 day", periods=10),
- )
+ zip(
+ timedelta_range("0 days", periods=10),
+ timedelta_range("1 day", periods=10),
),
],
)
def test_to_tuples(self, tuples):
# GH 18756
+ tuples = list(tuples)
idx = IntervalIndex.from_tuples(tuples)
result = idx.to_tuples()
expected = Index(com.asarray_tuplesafe(tuples))
diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py
index 6c6d9022b1af3..1bbeedac3fb10 100644
--- a/pandas/tests/indexes/multi/test_duplicates.py
+++ b/pandas/tests/indexes/multi/test_duplicates.py
@@ -243,13 +243,14 @@ def f(a):
@pytest.mark.parametrize(
"keep, expected",
[
- ("first", np.array([False, False, False, True, True, False])),
- ("last", np.array([False, True, True, False, False, False])),
- (False, np.array([False, True, True, True, True, False])),
+ ("first", [False, False, False, True, True, False]),
+ ("last", [False, True, True, False, False, False]),
+ (False, [False, True, True, True, True, False]),
],
)
def test_duplicated(idx_dup, keep, expected):
result = idx_dup.duplicated(keep=keep)
+ expected = np.array(expected)
tm.assert_numpy_array_equal(result, expected)
@@ -319,14 +320,7 @@ def test_duplicated_drop_duplicates():
tm.assert_index_equal(idx.drop_duplicates(keep=False), expected)
-@pytest.mark.parametrize(
- "dtype",
- [
- np.complex64,
- np.complex128,
- ],
-)
-def test_duplicated_series_complex_numbers(dtype):
+def test_duplicated_series_complex_numbers(complex_dtype):
# GH 17927
expected = Series(
[False, False, False, True, False, False, False, True, False, True],
@@ -345,7 +339,7 @@ def test_duplicated_series_complex_numbers(dtype):
np.nan,
np.nan + np.nan * 1j,
],
- dtype=dtype,
+ dtype=complex_dtype,
).duplicated()
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py
index 5e2d3c23da645..f426a3ee42566 100644
--- a/pandas/tests/indexes/multi/test_indexing.py
+++ b/pandas/tests/indexes/multi/test_indexing.py
@@ -560,27 +560,26 @@ def test_getitem_group_select(idx):
assert sorted_idx.get_loc("foo") == slice(0, 2)
-@pytest.mark.parametrize("ind1", [[True] * 5, Index([True] * 5)])
-@pytest.mark.parametrize(
- "ind2",
- [[True, False, True, False, False], Index([True, False, True, False, False])],
-)
-def test_getitem_bool_index_all(ind1, ind2):
+@pytest.mark.parametrize("box", [list, Index])
+def test_getitem_bool_index_all(box):
# GH#22533
+ ind1 = box([True] * 5)
idx = MultiIndex.from_tuples([(10, 1), (20, 2), (30, 3), (40, 4), (50, 5)])
tm.assert_index_equal(idx[ind1], idx)
+ ind2 = box([True, False, True, False, False])
expected = MultiIndex.from_tuples([(10, 1), (30, 3)])
tm.assert_index_equal(idx[ind2], expected)
-@pytest.mark.parametrize("ind1", [[True], Index([True])])
-@pytest.mark.parametrize("ind2", [[False], Index([False])])
-def test_getitem_bool_index_single(ind1, ind2):
+@pytest.mark.parametrize("box", [list, Index])
+def test_getitem_bool_index_single(box):
# GH#22533
+ ind1 = box([True])
idx = MultiIndex.from_tuples([(10, 1)])
tm.assert_index_equal(idx[ind1], idx)
+ ind2 = box([False])
expected = MultiIndex(
levels=[np.array([], dtype=np.int64), np.array([], dtype=np.int64)],
codes=[[], []],
diff --git a/pandas/tests/indexes/multi/test_isin.py b/pandas/tests/indexes/multi/test_isin.py
index 68fdf25359f1b..92ac2468d5993 100644
--- a/pandas/tests/indexes/multi/test_isin.py
+++ b/pandas/tests/indexes/multi/test_isin.py
@@ -75,15 +75,16 @@ def test_isin_level_kwarg():
@pytest.mark.parametrize(
"labels,expected,level",
[
- ([("b", np.nan)], np.array([False, False, True]), None),
- ([np.nan, "a"], np.array([True, True, False]), 0),
- (["d", np.nan], np.array([False, True, True]), 1),
+ ([("b", np.nan)], [False, False, True], None),
+ ([np.nan, "a"], [True, True, False], 0),
+ (["d", np.nan], [False, True, True], 1),
],
)
def test_isin_multi_index_with_missing_value(labels, expected, level):
# GH 19132
midx = MultiIndex.from_arrays([[np.nan, "a", "b"], ["c", "d", np.nan]])
result = midx.isin(labels, level=level)
+ expected = np.array(expected)
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py
index edd0feaaa1159..3fb428fecea41 100644
--- a/pandas/tests/indexes/multi/test_join.py
+++ b/pandas/tests/indexes/multi/test_join.py
@@ -12,10 +12,9 @@
import pandas._testing as tm
-@pytest.mark.parametrize(
- "other", [Index(["three", "one", "two"]), Index(["one"]), Index(["one", "three"])]
-)
+@pytest.mark.parametrize("other", [["three", "one", "two"], ["one"], ["one", "three"]])
def test_join_level(idx, other, join_type):
+ other = Index(other)
join_index, lidx, ridx = other.join(
idx, how=join_type, level="second", return_indexers=True
)
diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py
index 0abb56ecf9de7..9354984538c58 100644
--- a/pandas/tests/indexes/multi/test_setops.py
+++ b/pandas/tests/indexes/multi/test_setops.py
@@ -711,17 +711,11 @@ def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names):
"a",
[pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]],
)
-@pytest.mark.parametrize(
- "b",
- [
- pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True),
- pd.Categorical(["a", "b"], categories=["b", "a"]),
- ],
-)
-def test_intersection_with_non_lex_sorted_categories(a, b):
+@pytest.mark.parametrize("b_ordered", [True, False])
+def test_intersection_with_non_lex_sorted_categories(a, b_ordered):
# GH#49974
other = ["1", "2"]
-
+ b = pd.Categorical(["a", "b"], categories=["b", "a"], ordered=b_ordered)
df1 = DataFrame({"x": a, "y": other})
df2 = DataFrame({"x": b, "y": other})
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index 29f8a0a5a5932..43adc09774914 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -110,16 +110,16 @@ def test_get_indexer(self):
@pytest.mark.parametrize(
"expected,method",
[
- (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),
- (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),
- (np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),
- (np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),
+ ([-1, 0, 0, 1, 1], "pad"),
+ ([-1, 0, 0, 1, 1], "ffill"),
+ ([0, 0, 1, 1, 2], "backfill"),
+ ([0, 0, 1, 1, 2], "bfill"),
],
)
def test_get_indexer_methods(self, reverse, expected, method):
index1 = Index([1, 2, 3, 4, 5])
index2 = Index([2, 4, 6])
-
+ expected = np.array(expected, dtype=np.intp)
if reverse:
index1 = index1[::-1]
expected = expected[::-1]
@@ -166,12 +166,11 @@ def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
@pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
@pytest.mark.parametrize(
"tolerance, expected",
- list(
- zip(
- [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],
- [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],
- )
- ),
+ [
+ [[0.3, 0.3, 0.1], [0, 2, -1]],
+ [[0.2, 0.1, 0.1], [0, -1, -1]],
+ [[0.1, 0.5, 0.5], [-1, 2, 9]],
+ ],
)
def test_get_indexer_nearest_listlike_tolerance(
self, tolerance, expected, listtype
diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py
index 102560852e8e4..e9e5a57dfe9e5 100644
--- a/pandas/tests/indexes/numeric/test_setops.py
+++ b/pandas/tests/indexes/numeric/test_setops.py
@@ -113,13 +113,14 @@ def test_intersection_uint64_outside_int64_range(self):
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
- "index2,keeps_name",
+ "index2_name,keeps_name",
[
- (Index([4, 7, 6, 5, 3], name="index"), True),
- (Index([4, 7, 6, 5, 3], name="other"), False),
+ ("index", True),
+ ("other", False),
],
)
- def test_intersection_monotonic(self, index2, keeps_name, sort):
+ def test_intersection_monotonic(self, index2_name, keeps_name, sort):
+ index2 = Index([4, 7, 6, 5, 3], name=index2_name)
index1 = Index([5, 3, 2, 4, 1], name="index")
expected = Index([5, 3, 4])
diff --git a/pandas/tests/indexes/object/test_indexing.py b/pandas/tests/indexes/object/test_indexing.py
index ebf9dac715f8d..039836da75cd5 100644
--- a/pandas/tests/indexes/object/test_indexing.py
+++ b/pandas/tests/indexes/object/test_indexing.py
@@ -18,11 +18,12 @@ class TestGetIndexer:
@pytest.mark.parametrize(
"method,expected",
[
- ("pad", np.array([-1, 0, 1, 1], dtype=np.intp)),
- ("backfill", np.array([0, 0, 1, -1], dtype=np.intp)),
+ ("pad", [-1, 0, 1, 1]),
+ ("backfill", [0, 0, 1, -1]),
],
)
def test_get_indexer_strings(self, method, expected):
+ expected = np.array(expected, dtype=np.intp)
index = Index(["b", "c"])
actual = index.get_indexer(["a", "b", "c", "d"], method=method)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 158cba9dfdded..77ce687d51693 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -844,12 +844,14 @@ def test_is_monotonic_incomparable(self, attr):
@pytest.mark.parametrize(
"index,expected",
[
- (Index(["qux", "baz", "foo", "bar"]), np.array([False, False, True, True])),
- (Index([]), np.array([], dtype=bool)), # empty
+ (["qux", "baz", "foo", "bar"], [False, False, True, True]),
+ ([], []), # empty
],
)
def test_isin(self, values, index, expected):
+ index = Index(index)
result = index.isin(values)
+ expected = np.array(expected, dtype=bool)
tm.assert_numpy_array_equal(result, expected)
def test_isin_nan_common_object(
@@ -918,11 +920,12 @@ def test_isin_nan_common_float64(self, nulls_fixture, float_numpy_dtype):
@pytest.mark.parametrize(
"index",
[
- Index(["qux", "baz", "foo", "bar"]),
- Index([1.0, 2.0, 3.0, 4.0], dtype=np.float64),
+ ["qux", "baz", "foo", "bar"],
+ np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float64),
],
)
def test_isin_level_kwarg(self, level, index):
+ index = Index(index)
values = index.tolist()[-2:] + ["nonexisting"]
expected = np.array([False, False, True, True])
@@ -1078,10 +1081,11 @@ def test_str_bool_series_indexing(self):
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
- "index,expected", [(Index(list("abcd")), True), (Index(range(4)), False)]
+ "index,expected", [(list("abcd"), True), (range(4), False)]
)
def test_tab_completion(self, index, expected):
# GH 9910
+ index = Index(index)
result = "str" in dir(index)
assert result == expected
@@ -1164,15 +1168,11 @@ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):
index = Index(list("abc"))
assert index.reindex(labels)[0].dtype.type == index.dtype.type
- @pytest.mark.parametrize(
- "labels,dtype",
- [
- (DatetimeIndex([]), np.datetime64),
- ],
- )
- def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype):
+ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self):
# GH7774
index = Index(list("abc"))
+ labels = DatetimeIndex([])
+ dtype = np.datetime64
assert index.reindex(labels)[0].dtype.type == dtype
def test_reindex_doesnt_preserve_type_if_target_is_empty_index_numeric(
diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py
index 72641077c90fe..867d32e5c86a2 100644
--- a/pandas/tests/indexes/test_index_new.py
+++ b/pandas/tests/indexes/test_index_new.py
@@ -80,14 +80,10 @@ def test_construction_list_tuples_nan(self, na_value, vtype):
expected = MultiIndex.from_tuples(values)
tm.assert_index_equal(result, expected)
- @pytest.mark.parametrize(
- "dtype",
- [int, "int64", "int32", "int16", "int8", "uint64", "uint32", "uint16", "uint8"],
- )
- def test_constructor_int_dtype_float(self, dtype):
+ def test_constructor_int_dtype_float(self, any_int_numpy_dtype):
# GH#18400
- expected = Index([0, 1, 2, 3], dtype=dtype)
- result = Index([0.0, 1.0, 2.0, 3.0], dtype=dtype)
+ expected = Index([0, 1, 2, 3], dtype=any_int_numpy_dtype)
+ result = Index([0.0, 1.0, 2.0, 3.0], dtype=any_int_numpy_dtype)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("cast_index", [True, False])
@@ -332,11 +328,12 @@ def test_constructor_dtypes_to_categorical(self, vals):
@pytest.mark.parametrize(
"vals",
[
- Index(np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")])),
- Index([datetime(2011, 1, 1), datetime(2011, 1, 2)]),
+ np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")]),
+ [datetime(2011, 1, 1), datetime(2011, 1, 2)],
],
)
def test_constructor_dtypes_to_datetime(self, cast_index, vals):
+ vals = Index(vals)
if cast_index:
index = Index(vals, dtype=object)
assert isinstance(index, Index)
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 1ea47f636ac9b..e6716239cca5a 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -92,15 +92,16 @@ class TestContains:
@pytest.mark.parametrize(
"index,val",
[
- (Index([0, 1, 2]), 2),
- (Index([0, 1, "2"]), "2"),
- (Index([0, 1, 2, np.inf, 4]), 4),
- (Index([0, 1, 2, np.nan, 4]), 4),
- (Index([0, 1, 2, np.inf]), np.inf),
- (Index([0, 1, 2, np.nan]), np.nan),
+ ([0, 1, 2], 2),
+ ([0, 1, "2"], "2"),
+ ([0, 1, 2, np.inf, 4], 4),
+ ([0, 1, 2, np.nan, 4], 4),
+ ([0, 1, 2, np.inf], np.inf),
+ ([0, 1, 2, np.nan], np.nan),
],
)
def test_index_contains(self, index, val):
+ index = Index(index)
assert val in index
@pytest.mark.parametrize(
@@ -123,18 +124,16 @@ def test_index_contains(self, index, val):
def test_index_not_contains(self, index, val):
assert val not in index
- @pytest.mark.parametrize(
- "index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
- )
- def test_mixed_index_contains(self, index, val):
+ @pytest.mark.parametrize("val", [0, "2"])
+ def test_mixed_index_contains(self, val):
# GH#19860
+ index = Index([0, 1, "2"])
assert val in index
- @pytest.mark.parametrize(
- "index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
- )
+ @pytest.mark.parametrize("val", ["1", 2])
def test_mixed_index_not_contains(self, index, val):
# GH#19860
+ index = Index([0, 1, "2"])
assert val not in index
def test_contains_with_float_index(self, any_real_numpy_dtype):
@@ -303,12 +302,10 @@ def test_putmask_with_wrong_mask(self, index):
index.putmask("foo", fill)
-@pytest.mark.parametrize(
- "idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
-)
+@pytest.mark.parametrize("idx", [[1, 2, 3], [0.1, 0.2, 0.3], ["a", "b", "c"]])
def test_getitem_deprecated_float(idx):
# https://github.com/pandas-dev/pandas/issues/34191
-
+ idx = Index(idx)
msg = "Indexing with a float is no longer supported"
with pytest.raises(IndexError, match=msg):
idx[1.0]
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index 8f4dd1c64236a..27b54ea66f0ac 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -721,14 +721,15 @@ def test_intersection(self, index, sort):
assert inter is first
@pytest.mark.parametrize(
- "index2,keeps_name",
+ "index2_name,keeps_name",
[
- (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name
- (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names
- (Index([3, 4, 5, 6, 7]), False),
+ ("index", True), # preserve same name
+ ("other", False), # drop diff names
+ (None, False),
],
)
- def test_intersection_name_preservation(self, index2, keeps_name, sort):
+ def test_intersection_name_preservation(self, index2_name, keeps_name, sort):
+ index2 = Index([3, 4, 5, 6, 7], name=index2_name)
index1 = Index([1, 2, 3, 4, 5], name="index")
expected = Index([3, 4, 5])
result = index1.intersection(index2, sort)
@@ -915,11 +916,13 @@ def test_symmetric_difference_mi(self, sort):
@pytest.mark.parametrize(
"index2,expected",
[
- (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])),
- (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])),
+ ([0, 1, np.nan], [2.0, 3.0, 0.0]),
+ ([0, 1], [np.nan, 2.0, 3.0, 0.0]),
],
)
def test_symmetric_difference_missing(self, index2, expected, sort):
+ index2 = Index(index2)
+ expected = Index(expected)
# GH#13514 change: {nan} - {nan} == {}
# (GH#6444, sorting of nans, is no longer an issue)
index1 = Index([1, np.nan, 2, 3])
diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py
index cabfee9aa040a..b72ef57475305 100644
--- a/pandas/tests/indexing/interval/test_interval.py
+++ b/pandas/tests/indexing/interval/test_interval.py
@@ -211,10 +211,7 @@ def test_mi_intervalindex_slicing_with_scalar(self):
tm.assert_series_equal(result, expected)
@pytest.mark.xfail(not IS64, reason="GH 23440")
- @pytest.mark.parametrize(
- "base",
- [101, 1010],
- )
+ @pytest.mark.parametrize("base", [101, 1010])
def test_reindex_behavior_with_interval_index(self, base):
# GH 51826
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index c897afaeeee0e..a9aeba0c199f9 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1383,14 +1383,12 @@ def test_loc_getitem_timedelta_0seconds(self):
result = df.loc["0s":, :]
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize(
- "val,expected", [(2**63 - 1, Series([1])), (2**63, Series([2]))]
- )
+ @pytest.mark.parametrize("val,expected", [(2**63 - 1, 1), (2**63, 2)])
def test_loc_getitem_uint64_scalar(self, val, expected):
# see GH#19399
df = DataFrame([1, 2], index=[2**63 - 1, 2**63])
result = df.loc[val]
-
+ expected = Series([expected])
expected.name = val
tm.assert_series_equal(result, expected)
@@ -2168,12 +2166,11 @@ def test_loc_setitem_with_expansion_nonunique_index(self, index):
)
tm.assert_frame_equal(df, expected)
- @pytest.mark.parametrize(
- "dtype", ["Int32", "Int64", "UInt32", "UInt64", "Float32", "Float64"]
- )
- def test_loc_setitem_with_expansion_preserves_nullable_int(self, dtype):
+ def test_loc_setitem_with_expansion_preserves_nullable_int(
+ self, any_numeric_ea_dtype
+ ):
# GH#42099
- ser = Series([0, 1, 2, 3], dtype=dtype)
+ ser = Series([0, 1, 2, 3], dtype=any_numeric_ea_dtype)
df = DataFrame({"data": ser})
result = DataFrame(index=df.index)
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 15712f36da4ca..04a25317c8017 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -562,25 +562,21 @@ def test_reader_dtype(self, read_ext):
[
(
None,
- DataFrame(
- {
- "a": [1, 2, 3, 4],
- "b": [2.5, 3.5, 4.5, 5.5],
- "c": [1, 2, 3, 4],
- "d": [1.0, 2.0, np.nan, 4.0],
- }
- ),
+ {
+ "a": [1, 2, 3, 4],
+ "b": [2.5, 3.5, 4.5, 5.5],
+ "c": [1, 2, 3, 4],
+ "d": [1.0, 2.0, np.nan, 4.0],
+ },
),
(
{"a": "float64", "b": "float32", "c": str, "d": str},
- DataFrame(
- {
- "a": Series([1, 2, 3, 4], dtype="float64"),
- "b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),
- "c": Series(["001", "002", "003", "004"], dtype=object),
- "d": Series(["1", "2", np.nan, "4"], dtype=object),
- }
- ),
+ {
+ "a": Series([1, 2, 3, 4], dtype="float64"),
+ "b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),
+ "c": Series(["001", "002", "003", "004"], dtype=object),
+ "d": Series(["1", "2", np.nan, "4"], dtype=object),
+ },
),
],
)
@@ -589,6 +585,7 @@ def test_reader_dtype_str(self, read_ext, dtype, expected):
basename = "testdtype"
actual = pd.read_excel(basename + read_ext, dtype=dtype)
+ expected = DataFrame(expected)
tm.assert_frame_equal(actual, expected)
def test_dtype_backend(self, read_ext, dtype_backend, engine):
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 8c003723c1c71..76a138a295bda 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -90,7 +90,7 @@ def set_engine(engine, ext):
class TestRoundTrip:
@pytest.mark.parametrize(
"header,expected",
- [(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))],
+ [(None, [np.nan] * 4), (0, {"Unnamed: 0": [np.nan] * 3})],
)
def test_read_one_empty_col_no_header(self, ext, header, expected):
# xref gh-12292
@@ -102,14 +102,14 @@ def test_read_one_empty_col_no_header(self, ext, header, expected):
result = pd.read_excel(
path, sheet_name=filename, usecols=[0], header=header
)
-
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
- "header,expected",
- [(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))],
+ "header,expected_extra",
+ [(None, [0]), (0, [])],
)
- def test_read_one_empty_col_with_header(self, ext, header, expected):
+ def test_read_one_empty_col_with_header(self, ext, header, expected_extra):
filename = "with_header"
df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])
@@ -118,7 +118,7 @@ def test_read_one_empty_col_with_header(self, ext, header, expected):
result = pd.read_excel(
path, sheet_name=filename, usecols=[0], header=header
)
-
+ expected = DataFrame(expected_extra + [np.nan] * 4)
tm.assert_frame_equal(result, expected)
def test_set_column_names_in_parameter(self, ext):
diff --git a/pandas/tests/io/formats/style/test_highlight.py b/pandas/tests/io/formats/style/test_highlight.py
index 3d59719010ee0..5d19e9c14d534 100644
--- a/pandas/tests/io/formats/style/test_highlight.py
+++ b/pandas/tests/io/formats/style/test_highlight.py
@@ -198,16 +198,17 @@ def test_highlight_quantile(styler, kwargs):
],
)
@pytest.mark.parametrize(
- "df",
+ "dtype",
[
- DataFrame([[0, 10], [20, 30]], dtype=int),
- DataFrame([[0, 10], [20, 30]], dtype=float),
- DataFrame([[0, 10], [20, 30]], dtype="datetime64[ns]"),
- DataFrame([[0, 10], [20, 30]], dtype=str),
- DataFrame([[0, 10], [20, 30]], dtype="timedelta64[ns]"),
+ int,
+ float,
+ "datetime64[ns]",
+ str,
+ "timedelta64[ns]",
],
)
-def test_all_highlight_dtypes(f, kwargs, df):
+def test_all_highlight_dtypes(f, kwargs, dtype):
+ df = DataFrame([[0, 10], [20, 30]], dtype=dtype)
if f == "highlight_quantile" and isinstance(df.iloc[0, 0], (str)):
return None # quantile incompatible with str
if f == "highlight_between":
diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py
index fb7a77f1ddb27..ef7bfb11d81d8 100644
--- a/pandas/tests/io/formats/style/test_matplotlib.py
+++ b/pandas/tests/io/formats/style/test_matplotlib.py
@@ -260,15 +260,10 @@ def test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gma
assert expected.ctx == result.ctx
-@pytest.mark.parametrize(
- "gmap, axis",
- [
- (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1),
- (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0),
- ],
-)
-def test_background_gradient_gmap_wrong_dataframe(styler_blank, gmap, axis):
+@pytest.mark.parametrize("axis", [1, 0])
+def test_background_gradient_gmap_wrong_dataframe(styler_blank, axis):
# test giving a gmap in DataFrame but with wrong axis
+ gmap = DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"])
msg = "'gmap' is a DataFrame but underlying data for operations is a Series"
with pytest.raises(ValueError, match=msg):
styler_blank.background_gradient(gmap=gmap, axis=axis)._compute()
@@ -321,10 +316,7 @@ def test_bar_color_raises(df):
df.style.bar(color="something", cmap="something else").to_html()
-@pytest.mark.parametrize(
- "plot_method",
- ["scatter", "hexbin"],
-)
+@pytest.mark.parametrize("plot_method", ["scatter", "hexbin"])
def test_pass_colormap_instance(df, plot_method):
# https://github.com/pandas-dev/pandas/issues/49374
cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]])
diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py
index 7f1443c3ee66b..eb221686dd165 100644
--- a/pandas/tests/io/formats/style/test_to_latex.py
+++ b/pandas/tests/io/formats/style/test_to_latex.py
@@ -1058,10 +1058,10 @@ def test_concat_chain():
@pytest.mark.parametrize(
- "df, expected",
+ "columns, expected",
[
(
- DataFrame(),
+ None,
dedent(
"""\
\\begin{tabular}{l}
@@ -1070,7 +1070,7 @@ def test_concat_chain():
),
),
(
- DataFrame(columns=["a", "b", "c"]),
+ ["a", "b", "c"],
dedent(
"""\
\\begin{tabular}{llll}
@@ -1084,7 +1084,8 @@ def test_concat_chain():
@pytest.mark.parametrize(
"clines", [None, "all;data", "all;index", "skip-last;data", "skip-last;index"]
)
-def test_empty_clines(df: DataFrame, expected: str, clines: str):
+def test_empty_clines(columns, expected: str, clines: str):
# GH 47203
+ df = DataFrame(columns=columns)
result = df.style.to_latex(clines=clines)
assert result == expected
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index 790ba92f70c40..e85b4cb29390e 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -136,13 +136,14 @@ def test_to_html_with_empty_string_label():
@pytest.mark.parametrize(
- "df,expected",
+ "df_data,expected",
[
- (DataFrame({"\u03c3": np.arange(10.0)}), "unicode_1"),
- (DataFrame({"A": ["\u03c3"]}), "unicode_2"),
+ ({"\u03c3": np.arange(10.0)}, "unicode_1"),
+ ({"A": ["\u03c3"]}, "unicode_2"),
],
)
-def test_to_html_unicode(df, expected, datapath):
+def test_to_html_unicode(df_data, expected, datapath):
+ df = DataFrame(df_data)
expected = expected_html(datapath, expected)
result = df.to_html()
assert result == expected
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 4c8cd4b6a2b8e..304aff0002209 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -283,14 +283,15 @@ def test_to_latex_longtable_without_index(self):
assert result == expected
@pytest.mark.parametrize(
- "df, expected_number",
+ "df_data, expected_number",
[
- (DataFrame({"a": [1, 2]}), 1),
- (DataFrame({"a": [1, 2], "b": [3, 4]}), 2),
- (DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}), 3),
+ ({"a": [1, 2]}, 1),
+ ({"a": [1, 2], "b": [3, 4]}, 2),
+ ({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, 3),
],
)
- def test_to_latex_longtable_continued_on_next_page(self, df, expected_number):
+ def test_to_latex_longtable_continued_on_next_page(self, df_data, expected_number):
+ df = DataFrame(df_data)
result = df.to_latex(index=False, longtable=True)
assert rf"\multicolumn{{{expected_number}}}" in result
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index d5ea470af79d6..28b613fa1f6f6 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -165,11 +165,9 @@ def test_as_json_table_type_bool_data(self, bool_type):
def test_as_json_table_type_date_data(self, date_data):
assert as_json_table_type(date_data.dtype) == "datetime"
- @pytest.mark.parametrize(
- "str_data",
- [pd.Series(["a", "b"], dtype=object), pd.Index(["a", "b"], dtype=object)],
- )
- def test_as_json_table_type_string_data(self, str_data):
+ @pytest.mark.parametrize("klass", [pd.Series, pd.Index])
+ def test_as_json_table_type_string_data(self, klass):
+ str_data = klass(["a", "b"], dtype=object)
assert as_json_table_type(str_data.dtype) == "string"
@pytest.mark.parametrize(
@@ -700,20 +698,27 @@ class TestTableOrientReader:
},
],
)
- def test_read_json_table_orient(self, index_nm, vals, recwarn):
+ def test_read_json_table_orient(self, index_nm, vals):
df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))
- out = df.to_json(orient="table")
+ out = StringIO(df.to_json(orient="table"))
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
- @pytest.mark.parametrize("index_nm", [None, "idx", "index"])
@pytest.mark.parametrize(
- "vals",
- [{"timedeltas": pd.timedelta_range("1h", periods=4, freq="min")}],
+ "index_nm",
+ [
+ None,
+ "idx",
+ pytest.param(
+ "index",
+ marks=pytest.mark.filterwarnings("ignore:Index name:UserWarning"),
+ ),
+ ],
)
- def test_read_json_table_orient_raises(self, index_nm, vals, recwarn):
+ def test_read_json_table_orient_raises(self, index_nm):
+ vals = {"timedeltas": pd.timedelta_range("1h", periods=4, freq="min")}
df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))
- out = df.to_json(orient="table")
+ out = StringIO(df.to_json(orient="table"))
with pytest.raises(NotImplementedError, match="can not yet read "):
pd.read_json(out, orient="table")
@@ -744,14 +749,14 @@ def test_read_json_table_orient_raises(self, index_nm, vals, recwarn):
},
],
)
- def test_read_json_table_period_orient(self, index_nm, vals, recwarn):
+ def test_read_json_table_period_orient(self, index_nm, vals):
df = DataFrame(
vals,
index=pd.Index(
(pd.Period(f"2022Q{q}") for q in range(1, 5)), name=index_nm
),
)
- out = df.to_json(orient="table")
+ out = StringIO(df.to_json(orient="table"))
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
@@ -787,10 +792,10 @@ def test_read_json_table_period_orient(self, index_nm, vals, recwarn):
},
],
)
- def test_read_json_table_timezones_orient(self, idx, vals, recwarn):
+ def test_read_json_table_timezones_orient(self, idx, vals):
# GH 35973
df = DataFrame(vals, index=idx)
- out = df.to_json(orient="table")
+ out = StringIO(df.to_json(orient="table"))
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
@@ -861,12 +866,12 @@ def test_read_json_orient_table_old_schema_version(self):
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("freq", ["M", "2M", "Q", "2Q", "Y", "2Y"])
- def test_read_json_table_orient_period_depr_freq(self, freq, recwarn):
+ def test_read_json_table_orient_period_depr_freq(self, freq):
# GH#9586
df = DataFrame(
{"ints": [1, 2]},
index=pd.PeriodIndex(["2020-01", "2021-06"], freq=freq),
)
- out = df.to_json(orient="table")
+ out = StringIO(df.to_json(orient="table"))
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
index 015b27d0b3606..68c7a96920533 100644
--- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
+++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
@@ -61,54 +61,33 @@ def test_build_table_schema(self):
class TestTableSchemaType:
- @pytest.mark.parametrize(
- "date_data",
- [
- DateArray([dt.date(2021, 10, 10)]),
- DateArray(dt.date(2021, 10, 10)),
- Series(DateArray(dt.date(2021, 10, 10))),
- ],
- )
- def test_as_json_table_type_ext_date_array_dtype(self, date_data):
+ @pytest.mark.parametrize("box", [lambda x: x, Series])
+ def test_as_json_table_type_ext_date_array_dtype(self, box):
+ date_data = box(DateArray([dt.date(2021, 10, 10)]))
assert as_json_table_type(date_data.dtype) == "any"
def test_as_json_table_type_ext_date_dtype(self):
assert as_json_table_type(DateDtype()) == "any"
- @pytest.mark.parametrize(
- "decimal_data",
- [
- DecimalArray([decimal.Decimal(10)]),
- Series(DecimalArray([decimal.Decimal(10)])),
- ],
- )
- def test_as_json_table_type_ext_decimal_array_dtype(self, decimal_data):
+ @pytest.mark.parametrize("box", [lambda x: x, Series])
+ def test_as_json_table_type_ext_decimal_array_dtype(self, box):
+ decimal_data = box(DecimalArray([decimal.Decimal(10)]))
assert as_json_table_type(decimal_data.dtype) == "number"
def test_as_json_table_type_ext_decimal_dtype(self):
assert as_json_table_type(DecimalDtype()) == "number"
- @pytest.mark.parametrize(
- "string_data",
- [
- array(["pandas"], dtype="string"),
- Series(array(["pandas"], dtype="string")),
- ],
- )
- def test_as_json_table_type_ext_string_array_dtype(self, string_data):
+ @pytest.mark.parametrize("box", [lambda x: x, Series])
+ def test_as_json_table_type_ext_string_array_dtype(self, box):
+ string_data = box(array(["pandas"], dtype="string"))
assert as_json_table_type(string_data.dtype) == "any"
def test_as_json_table_type_ext_string_dtype(self):
assert as_json_table_type(StringDtype()) == "any"
- @pytest.mark.parametrize(
- "integer_data",
- [
- array([10], dtype="Int64"),
- Series(array([10], dtype="Int64")),
- ],
- )
- def test_as_json_table_type_ext_integer_array_dtype(self, integer_data):
+ @pytest.mark.parametrize("box", [lambda x: x, Series])
+ def test_as_json_table_type_ext_integer_array_dtype(self, box):
+ integer_data = box(array([10], dtype="Int64"))
assert as_json_table_type(integer_data.dtype) == "integer"
def test_as_json_table_type_ext_integer_dtype(self):
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 7254fd7cb345d..2a2b4053be565 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -1895,17 +1895,12 @@ def test_frame_int_overflow(self):
result = read_json(StringIO(encoded_json))
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize(
- "dataframe,expected",
- [
- (
- DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}),
- '{"(0, \'x\')":1,"(0, \'y\')":"a","(1, \'x\')":2,'
- '"(1, \'y\')":"b","(2, \'x\')":3,"(2, \'y\')":"c"}',
- )
- ],
- )
- def test_json_multiindex(self, dataframe, expected):
+ def test_json_multiindex(self):
+ dataframe = DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]})
+ expected = (
+ '{"(0, \'x\')":1,"(0, \'y\')":"a","(1, \'x\')":2,'
+ '"(1, \'y\')":"b","(2, \'x\')":3,"(2, \'y\')":"c"}'
+ )
series = dataframe.stack(future_stack=True)
result = series.to_json(orient="index")
assert result == expected
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index c7d2a5845b50e..ce7bb74240c53 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -177,10 +177,7 @@ def test_encode_dict_with_unicode_keys(self, unicode_key):
unicode_dict = {unicode_key: "value1"}
assert unicode_dict == ujson.ujson_loads(ujson.ujson_dumps(unicode_dict))
- @pytest.mark.parametrize(
- "double_input",
- [math.pi, -math.pi], # Should work with negatives too.
- )
+ @pytest.mark.parametrize("double_input", [math.pi, -math.pi])
def test_encode_double_conversion(self, double_input):
output = ujson.ujson_dumps(double_input)
assert round(double_input, 5) == round(json.loads(output), 5)
@@ -520,10 +517,7 @@ def test_decode_invalid_dict(self, invalid_dict):
with pytest.raises(ValueError, match=msg):
ujson.ujson_loads(invalid_dict)
- @pytest.mark.parametrize(
- "numeric_int_as_str",
- ["31337", "-31337"], # Should work with negatives.
- )
+ @pytest.mark.parametrize("numeric_int_as_str", ["31337", "-31337"])
def test_decode_numeric_int(self, numeric_int_as_str):
assert int(numeric_int_as_str) == ujson.ujson_loads(numeric_int_as_str)
diff --git a/pandas/tests/io/parser/common/test_index.py b/pandas/tests/io/parser/common/test_index.py
index 038c684c90c9e..7cdaac1a284cd 100644
--- a/pandas/tests/io/parser/common/test_index.py
+++ b/pandas/tests/io/parser/common/test_index.py
@@ -145,20 +145,21 @@ def test_multi_index_no_level_names_implicit(all_parsers):
@xfail_pyarrow # TypeError: an integer is required
@pytest.mark.parametrize(
- "data,expected,header",
+ "data,columns,header",
[
- ("a,b", DataFrame(columns=["a", "b"]), [0]),
+ ("a,b", ["a", "b"], [0]),
(
"a,b\nc,d",
- DataFrame(columns=MultiIndex.from_tuples([("a", "c"), ("b", "d")])),
+ MultiIndex.from_tuples([("a", "c"), ("b", "d")]),
[0, 1],
),
],
)
@pytest.mark.parametrize("round_trip", [True, False])
-def test_multi_index_blank_df(all_parsers, data, expected, header, round_trip):
+def test_multi_index_blank_df(all_parsers, data, columns, header, round_trip):
# see gh-14545
parser = all_parsers
+ expected = DataFrame(columns=columns)
data = expected.to_csv(index=False) if round_trip else data
result = parser.read_csv(StringIO(data), header=header)
diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py
index a3167346c64ef..e77958b0e9acc 100644
--- a/pandas/tests/io/parser/common/test_ints.py
+++ b/pandas/tests/io/parser/common/test_ints.py
@@ -40,31 +40,29 @@ def test_int_conversion(all_parsers):
(
"A,B\nTrue,1\nFalse,2\nTrue,3",
{},
- DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]),
+ [[True, 1], [False, 2], [True, 3]],
),
(
"A,B\nYES,1\nno,2\nyes,3\nNo,3\nYes,3",
{"true_values": ["yes", "Yes", "YES"], "false_values": ["no", "NO", "No"]},
- DataFrame(
- [[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]],
- columns=["A", "B"],
- ),
+ [[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]],
),
(
"A,B\nTRUE,1\nFALSE,2\nTRUE,3",
{},
- DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]),
+ [[True, 1], [False, 2], [True, 3]],
),
(
"A,B\nfoo,bar\nbar,foo",
{"true_values": ["foo"], "false_values": ["bar"]},
- DataFrame([[True, False], [False, True]], columns=["A", "B"]),
+ [[True, False], [False, True]],
),
],
)
def test_parse_bool(all_parsers, data, kwargs, expected):
parser = all_parsers
result = parser.read_csv(StringIO(data), **kwargs)
+ expected = DataFrame(expected, columns=["A", "B"])
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py
index 155e52d76e895..f2d5c77121467 100644
--- a/pandas/tests/io/parser/test_encoding.py
+++ b/pandas/tests/io/parser/test_encoding.py
@@ -97,22 +97,22 @@ def test_unicode_encoding(all_parsers, csv_dir_path):
"data,kwargs,expected",
[
# Basic test
- ("a\n1", {}, DataFrame({"a": [1]})),
+ ("a\n1", {}, [1]),
# "Regular" quoting
- ('"a"\n1', {"quotechar": '"'}, DataFrame({"a": [1]})),
+ ('"a"\n1', {"quotechar": '"'}, [1]),
# Test in a data row instead of header
- ("b\n1", {"names": ["a"]}, DataFrame({"a": ["b", "1"]})),
+ ("b\n1", {"names": ["a"]}, ["b", "1"]),
# Test in empty data row with skipping
- ("\n1", {"names": ["a"], "skip_blank_lines": True}, DataFrame({"a": [1]})),
+ ("\n1", {"names": ["a"], "skip_blank_lines": True}, [1]),
# Test in empty data row without skipping
(
"\n1",
{"names": ["a"], "skip_blank_lines": False},
- DataFrame({"a": [np.nan, 1]}),
+ [np.nan, 1],
),
],
)
-def test_utf8_bom(all_parsers, data, kwargs, expected, request):
+def test_utf8_bom(all_parsers, data, kwargs, expected):
# see gh-4793
parser = all_parsers
bom = "\ufeff"
@@ -131,6 +131,7 @@ def _encode_data_with_bom(_data):
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs)
+ expected = DataFrame({"a": expected})
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py
index ca106fa772e82..6ebfc8f337c10 100644
--- a/pandas/tests/io/parser/test_na_values.py
+++ b/pandas/tests/io/parser/test_na_values.py
@@ -263,43 +263,35 @@ def test_na_value_dict_multi_index(all_parsers, index_col, expected):
[
(
{},
- DataFrame(
- {
- "A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
- "B": [1, 2, 3, 4, 5, 6, 7],
- "C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
- }
- ),
+ {
+ "A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
+ "B": [1, 2, 3, 4, 5, 6, 7],
+ "C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
+ },
),
(
{"na_values": {"A": [], "C": []}, "keep_default_na": False},
- DataFrame(
- {
- "A": ["a", "b", "", "d", "e", "nan", "g"],
- "B": [1, 2, 3, 4, 5, 6, 7],
- "C": ["one", "two", "three", "nan", "five", "", "seven"],
- }
- ),
+ {
+ "A": ["a", "b", "", "d", "e", "nan", "g"],
+ "B": [1, 2, 3, 4, 5, 6, 7],
+ "C": ["one", "two", "three", "nan", "five", "", "seven"],
+ },
),
(
{"na_values": ["a"], "keep_default_na": False},
- DataFrame(
- {
- "A": [np.nan, "b", "", "d", "e", "nan", "g"],
- "B": [1, 2, 3, 4, 5, 6, 7],
- "C": ["one", "two", "three", "nan", "five", "", "seven"],
- }
- ),
+ {
+ "A": [np.nan, "b", "", "d", "e", "nan", "g"],
+ "B": [1, 2, 3, 4, 5, 6, 7],
+ "C": ["one", "two", "three", "nan", "five", "", "seven"],
+ },
),
(
{"na_values": {"A": [], "C": []}},
- DataFrame(
- {
- "A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
- "B": [1, 2, 3, 4, 5, 6, 7],
- "C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
- }
- ),
+ {
+ "A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
+ "B": [1, 2, 3, 4, 5, 6, 7],
+ "C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
+ },
),
],
)
@@ -325,6 +317,7 @@ def test_na_values_keep_default(all_parsers, kwargs, expected, request):
request.applymarker(mark)
result = parser.read_csv(StringIO(data), **kwargs)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
@@ -561,10 +554,10 @@ def test_na_values_dict_col_index(all_parsers):
(
str(2**63) + "\n" + str(2**63 + 1),
{"na_values": [2**63]},
- DataFrame([str(2**63), str(2**63 + 1)]),
+ [str(2**63), str(2**63 + 1)],
),
- (str(2**63) + ",1" + "\n,2", {}, DataFrame([[str(2**63), 1], ["", 2]])),
- (str(2**63) + "\n1", {"na_values": [2**63]}, DataFrame([np.nan, 1])),
+ (str(2**63) + ",1" + "\n,2", {}, [[str(2**63), 1], ["", 2]]),
+ (str(2**63) + "\n1", {"na_values": [2**63]}, [np.nan, 1]),
],
)
def test_na_values_uint64(all_parsers, data, kwargs, expected, request):
@@ -581,6 +574,7 @@ def test_na_values_uint64(all_parsers, data, kwargs, expected, request):
request.applymarker(mark)
result = parser.read_csv(StringIO(data), header=None, **kwargs)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index 700dcde336cd1..9640d0dfe343f 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -1755,11 +1755,11 @@ def test_parse_date_column_with_empty_string(all_parsers):
[
(
"a\n135217135789158401\n1352171357E+5",
- DataFrame({"a": [135217135789158401, 135217135700000]}, dtype="float64"),
+ [135217135789158401, 135217135700000],
),
(
"a\n99999999999\n123456789012345\n1234E+0",
- DataFrame({"a": [99999999999, 123456789012345, 1234]}, dtype="float64"),
+ [99999999999, 123456789012345, 1234],
),
],
)
@@ -1772,6 +1772,7 @@ def test_parse_date_float(all_parsers, data, expected, parse_dates):
parser = all_parsers
result = parser.read_csv(StringIO(data), parse_dates=parse_dates)
+ expected = DataFrame({"a": expected}, dtype="float64")
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_python_parser_only.py b/pandas/tests/io/parser/test_python_parser_only.py
index dbd474c6ae0b9..dc3c527e82202 100644
--- a/pandas/tests/io/parser/test_python_parser_only.py
+++ b/pandas/tests/io/parser/test_python_parser_only.py
@@ -528,21 +528,17 @@ def test_no_thousand_convert_with_dot_for_non_numeric_cols(python_parser_only, d
[
(
{"a": str, "b": np.float64, "c": np.int64},
- DataFrame(
- {
- "b": [16000.1, 0, 23000],
- "c": [0, 4001, 131],
- }
- ),
+ {
+ "b": [16000.1, 0, 23000],
+ "c": [0, 4001, 131],
+ },
),
(
str,
- DataFrame(
- {
- "b": ["16,000.1", "0", "23,000"],
- "c": ["0", "4,001", "131"],
- }
- ),
+ {
+ "b": ["16,000.1", "0", "23,000"],
+ "c": ["0", "4,001", "131"],
+ },
),
],
)
@@ -560,5 +556,6 @@ def test_no_thousand_convert_for_non_numeric_cols(python_parser_only, dtype, exp
dtype=dtype,
thousands=",",
)
+ expected = DataFrame(expected)
expected.insert(0, "a", ["0000,7995", "3,03,001,00514", "4923,600,041"])
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py
index 0ca47ded7ba8a..3cd2351f84c7a 100644
--- a/pandas/tests/io/parser/test_skiprows.py
+++ b/pandas/tests/io/parser/test_skiprows.py
@@ -246,8 +246,8 @@ def test_skiprows_infield_quote(all_parsers):
@pytest.mark.parametrize(
"kwargs,expected",
[
- ({}, DataFrame({"1": [3, 5]})),
- ({"header": 0, "names": ["foo"]}, DataFrame({"foo": [3, 5]})),
+ ({}, "1"),
+ ({"header": 0, "names": ["foo"]}, "foo"),
],
)
def test_skip_rows_callable(all_parsers, kwargs, expected):
@@ -255,6 +255,7 @@ def test_skip_rows_callable(all_parsers, kwargs, expected):
data = "a\n1\n2\n3\n4\n5"
result = parser.read_csv(StringIO(data), skiprows=lambda x: x % 2 == 0, **kwargs)
+ expected = DataFrame({expected: [3, 5]})
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py
index 767fba666e417..214070b1ac5f2 100644
--- a/pandas/tests/io/parser/usecols/test_usecols_basic.py
+++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py
@@ -389,20 +389,18 @@ def test_incomplete_first_row(all_parsers, usecols):
"19,29,39\n" * 2 + "10,20,30,40",
[0, 1, 2],
{"header": None},
- DataFrame([[19, 29, 39], [19, 29, 39], [10, 20, 30]]),
+ [[19, 29, 39], [19, 29, 39], [10, 20, 30]],
),
# see gh-9549
(
("A,B,C\n1,2,3\n3,4,5\n1,2,4,5,1,6\n1,2,3,,,1,\n1,2,3\n5,6,7"),
["A", "B", "C"],
{},
- DataFrame(
- {
- "A": [1, 3, 1, 1, 1, 5],
- "B": [2, 4, 2, 2, 2, 6],
- "C": [3, 5, 4, 3, 3, 7],
- }
- ),
+ {
+ "A": [1, 3, 1, 1, 1, 5],
+ "B": [2, 4, 2, 2, 2, 6],
+ "C": [3, 5, 4, 3, 3, 7],
+ },
),
],
)
@@ -410,6 +408,7 @@ def test_uneven_length_cols(all_parsers, data, usecols, kwargs, expected):
# see gh-8985
parser = all_parsers
result = parser.read_csv(StringIO(data), usecols=usecols, **kwargs)
+ expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index 58ebdfe7696b4..2ab9f1ac8be1c 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -190,25 +190,19 @@ def test_categorical_nan_only_columns(tmp_path, setup_path):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize(
- "where, df, expected",
- [
- ('col=="q"', DataFrame({"col": ["a", "b", "s"]}), DataFrame({"col": []})),
- ('col=="a"', DataFrame({"col": ["a", "b", "s"]}), DataFrame({"col": ["a"]})),
- ],
-)
-def test_convert_value(
- tmp_path, setup_path, where: str, df: DataFrame, expected: DataFrame
-):
+@pytest.mark.parametrize("where, expected", [["q", []], ["a", ["a"]]])
+def test_convert_value(tmp_path, setup_path, where: str, expected):
# GH39420
# Check that read_hdf with categorical columns can filter by where condition.
+ df = DataFrame({"col": ["a", "b", "s"]})
df.col = df.col.astype("category")
max_widths = {"col": 1}
categorical_values = sorted(df.col.unique())
+ expected = DataFrame({"col": expected})
expected.col = expected.col.astype("category")
expected.col = expected.col.cat.set_categories(categorical_values)
path = tmp_path / setup_path
df.to_hdf(path, key="df", format="table", min_itemsize=max_widths)
- result = read_hdf(path, where=where)
+ result = read_hdf(path, where=f'col=="{where}"')
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index 6a2d460232165..420d82c3af7e3 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -1334,8 +1334,8 @@ def test_to_html_borderless(self):
@pytest.mark.parametrize(
"displayed_only,exp0,exp1",
[
- (True, DataFrame(["foo"]), None),
- (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"])),
+ (True, ["foo"], None),
+ (False, ["foo bar baz qux"], DataFrame(["foo"])),
],
)
def test_displayed_only(self, displayed_only, exp0, exp1, flavor_read_html):
@@ -1360,6 +1360,7 @@ def test_displayed_only(self, displayed_only, exp0, exp1, flavor_read_html):
</body>
</html>"""
+ exp0 = DataFrame(exp0)
dfs = flavor_read_html(StringIO(data), displayed_only=displayed_only)
tm.assert_frame_equal(dfs[0], exp0)
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index a6967732cf702..83a962ec26a7e 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -827,13 +827,7 @@ def test_s3_roundtrip(self, df_compat, s3_public_bucket, pa, s3so):
)
@pytest.mark.single_cpu
- @pytest.mark.parametrize(
- "partition_col",
- [
- ["A"],
- [],
- ],
- )
+ @pytest.mark.parametrize("partition_col", [["A"], []])
def test_s3_roundtrip_for_dir(
self, df_compat, s3_public_bucket, pa, partition_col, s3so
):
diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py
index 37251a58b0c11..a123f6dd52c08 100644
--- a/pandas/tests/io/xml/test_to_xml.py
+++ b/pandas/tests/io/xml/test_to_xml.py
@@ -298,10 +298,8 @@ def test_index_false_rename_row_root(xml_books, parser):
assert output == expected
-@pytest.mark.parametrize(
- "offset_index", [list(range(10, 13)), [str(i) for i in range(10, 13)]]
-)
-def test_index_false_with_offset_input_index(parser, offset_index, geom_df):
+@pytest.mark.parametrize("typ", [int, str])
+def test_index_false_with_offset_input_index(parser, typ, geom_df):
"""
Tests that the output does not contain the `<index>` field when the index of the
input Dataframe has an offset.
@@ -328,7 +326,7 @@ def test_index_false_with_offset_input_index(parser, offset_index, geom_df):
<sides>3.0</sides>
</row>
</data>"""
-
+ offset_index = [typ(i) for i in range(10, 13)]
offset_geom_df = geom_df.copy()
offset_geom_df.index = Index(offset_index)
output = offset_geom_df.to_xml(index=False, parser=parser)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56738 | 2024-01-05T01:12:19Z | 2024-01-10T21:50:17Z | 2024-01-10T21:50:17Z | 2024-01-10T21:50:20Z |
TST/CLN: Test parametrizations | diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 75259cb7e2f05..2dafaf277be8f 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -182,12 +182,12 @@ class TestDatetime64SeriesComparison:
@pytest.mark.parametrize(
"op, expected",
[
- (operator.eq, Series([False, False, True])),
- (operator.ne, Series([True, True, False])),
- (operator.lt, Series([False, False, False])),
- (operator.gt, Series([False, False, False])),
- (operator.ge, Series([False, False, True])),
- (operator.le, Series([False, False, True])),
+ (operator.eq, [False, False, True]),
+ (operator.ne, [True, True, False]),
+ (operator.lt, [False, False, False]),
+ (operator.gt, [False, False, False]),
+ (operator.ge, [False, False, True]),
+ (operator.le, [False, False, True]),
],
)
def test_nat_comparisons(
@@ -210,7 +210,7 @@ def test_nat_comparisons(
result = op(left, right)
- tm.assert_series_equal(result, expected)
+ tm.assert_series_equal(result, Series(expected))
@pytest.mark.parametrize(
"data",
@@ -1485,11 +1485,10 @@ def test_dt64arr_add_sub_DateOffsets(
@pytest.mark.parametrize(
"other",
[
- np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]),
- np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]),
- np.array( # matching offsets
- [pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)]
- ),
+ [pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
+ [pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()],
+ # matching offsets
+ [pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)],
],
)
@pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
@@ -1502,7 +1501,7 @@ def test_dt64arr_add_sub_offset_array(
tz = tz_naive_fixture
dti = date_range("2017-01-01", periods=2, tz=tz)
dtarr = tm.box_expected(dti, box_with_array)
-
+ other = np.array(other)
expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
expected = tm.box_expected(expected, box_with_array).astype(object)
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index b2007209dd5b9..3e9508bd2f504 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1960,19 +1960,20 @@ def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two):
two // tdser
@pytest.mark.parametrize(
- "vector",
- [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
- ids=lambda x: type(x).__name__,
+ "klass",
+ [np.array, Index, Series],
+ ids=lambda x: x.__name__,
)
def test_td64arr_rmul_numeric_array(
self,
box_with_array,
- vector,
+ klass,
any_real_numpy_dtype,
):
# GH#4521
# divide/multiply by integers
+ vector = klass([20, 30, 40])
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
vector = vector.astype(any_real_numpy_dtype)
@@ -1990,16 +1991,17 @@ def test_td64arr_rmul_numeric_array(
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
- "vector",
- [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
- ids=lambda x: type(x).__name__,
+ "klass",
+ [np.array, Index, Series],
+ ids=lambda x: x.__name__,
)
def test_td64arr_div_numeric_array(
- self, box_with_array, vector, any_real_numpy_dtype
+ self, box_with_array, klass, any_real_numpy_dtype
):
# GH#4521
# divide/multiply by integers
+ vector = klass([20, 30, 40])
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
vector = vector.astype(any_real_numpy_dtype)
diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py
index 5e1c5c64fa660..33c55b2090bd6 100644
--- a/pandas/tests/arrays/categorical/test_indexing.py
+++ b/pandas/tests/arrays/categorical/test_indexing.py
@@ -51,12 +51,10 @@ def test_setitem(self):
tm.assert_categorical_equal(c, expected)
- @pytest.mark.parametrize(
- "other",
- [Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])],
- )
- def test_setitem_same_but_unordered(self, other):
+ @pytest.mark.parametrize("categories", [None, ["b", "a"]])
+ def test_setitem_same_but_unordered(self, categories):
# GH-24142
+ other = Categorical(["b", "a"], categories=categories)
target = Categorical(["a", "b"], categories=["a", "b"])
mask = np.array([True, False])
target[mask] = other[mask]
diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py
index 4174d2adc810b..8778df832d4d7 100644
--- a/pandas/tests/arrays/categorical/test_operators.py
+++ b/pandas/tests/arrays/categorical/test_operators.py
@@ -307,29 +307,23 @@ def test_comparisons(self, data, reverse, base):
with pytest.raises(TypeError, match=msg):
a < cat_rev
- @pytest.mark.parametrize(
- "ctor",
- [
- lambda *args, **kwargs: Categorical(*args, **kwargs),
- lambda *args, **kwargs: Series(Categorical(*args, **kwargs)),
- ],
- )
- def test_unordered_different_order_equal(self, ctor):
+ @pytest.mark.parametrize("box", [lambda x: x, Series])
+ def test_unordered_different_order_equal(self, box):
# https://github.com/pandas-dev/pandas/issues/16014
- c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
- c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
+ c1 = box(Categorical(["a", "b"], categories=["a", "b"], ordered=False))
+ c2 = box(Categorical(["a", "b"], categories=["b", "a"], ordered=False))
assert (c1 == c2).all()
- c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
- c2 = ctor(["b", "a"], categories=["b", "a"], ordered=False)
+ c1 = box(Categorical(["a", "b"], categories=["a", "b"], ordered=False))
+ c2 = box(Categorical(["b", "a"], categories=["b", "a"], ordered=False))
assert (c1 != c2).all()
- c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
- c2 = ctor(["b", "b"], categories=["b", "a"], ordered=False)
+ c1 = box(Categorical(["a", "a"], categories=["a", "b"], ordered=False))
+ c2 = box(Categorical(["b", "b"], categories=["b", "a"], ordered=False))
assert (c1 != c2).all()
- c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
- c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
+ c1 = box(Categorical(["a", "a"], categories=["a", "b"], ordered=False))
+ c2 = box(Categorical(["a", "b"], categories=["b", "a"], ordered=False))
result = c1 == c2
tm.assert_numpy_array_equal(np.array(result), np.array([True, False]))
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 234f4092421e5..6fcbfe96a3df7 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -99,15 +99,15 @@ def test_construct_from_string_raises():
@pytest.mark.parametrize(
"dtype, expected",
[
- (SparseDtype(int), True),
- (SparseDtype(float), True),
- (SparseDtype(bool), True),
- (SparseDtype(object), False),
- (SparseDtype(str), False),
+ (int, True),
+ (float, True),
+ (bool, True),
+ (object, False),
+ (str, False),
],
)
def test_is_numeric(dtype, expected):
- assert dtype._is_numeric is expected
+ assert SparseDtype(dtype)._is_numeric is expected
def test_str_uses_object():
diff --git a/pandas/tests/arrays/sparse/test_reductions.py b/pandas/tests/arrays/sparse/test_reductions.py
index f44423d5e635c..4171d1213a0dc 100644
--- a/pandas/tests/arrays/sparse/test_reductions.py
+++ b/pandas/tests/arrays/sparse/test_reductions.py
@@ -126,13 +126,13 @@ def test_sum(self):
@pytest.mark.parametrize(
"arr",
- [np.array([0, 1, np.nan, 1]), np.array([0, 1, 1])],
+ [[0, 1, np.nan, 1], [0, 1, 1]],
)
@pytest.mark.parametrize("fill_value", [0, 1, np.nan])
@pytest.mark.parametrize("min_count, expected", [(3, 2), (4, np.nan)])
def test_sum_min_count(self, arr, fill_value, min_count, expected):
# GH#25777
- sparray = SparseArray(arr, fill_value=fill_value)
+ sparray = SparseArray(np.array(arr), fill_value=fill_value)
result = sparray.sum(min_count=min_count)
if np.isnan(expected):
assert np.isnan(result)
@@ -296,11 +296,9 @@ def test_argmax_argmin(self, arr, argmax_expected, argmin_expected):
assert argmax_result == argmax_expected
assert argmin_result == argmin_expected
- @pytest.mark.parametrize(
- "arr,method",
- [(SparseArray([]), "argmax"), (SparseArray([]), "argmin")],
- )
- def test_empty_array(self, arr, method):
+ @pytest.mark.parametrize("method", ["argmax", "argmin"])
+ def test_empty_array(self, method):
msg = f"attempt to get {method} of an empty sequence"
+ arr = SparseArray([])
with pytest.raises(ValueError, match=msg):
- arr.argmax() if method == "argmax" else arr.argmin()
+ getattr(arr, method)()
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index fe0f1f1454a55..ad35742a7b337 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -499,22 +499,23 @@ def test_to_numpy_dataframe_na_value(data, dtype, na_value):
@pytest.mark.parametrize(
- "data, expected",
+ "data, expected_data",
[
(
{"a": pd.array([1, 2, None])},
- np.array([[1.0], [2.0], [np.nan]], dtype=float),
+ [[1.0], [2.0], [np.nan]],
),
(
{"a": [1, 2, 3], "b": [1, 2, 3]},
- np.array([[1, 1], [2, 2], [3, 3]], dtype=float),
+ [[1, 1], [2, 2], [3, 3]],
),
],
)
-def test_to_numpy_dataframe_single_block(data, expected):
+def test_to_numpy_dataframe_single_block(data, expected_data):
# https://github.com/pandas-dev/pandas/issues/33820
df = pd.DataFrame(data)
result = df.to_numpy(dtype=float, na_value=np.nan)
+ expected = np.array(expected_data, dtype=float)
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 7969e684f5b04..b69fb573987f9 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -522,14 +522,15 @@ def test_series_negate(self, engine, parser):
"lhs",
[
# Float
- DataFrame(np.random.default_rng(2).standard_normal((5, 2))),
+ np.random.default_rng(2).standard_normal((5, 2)),
# Int
- DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))),
+ np.random.default_rng(2).integers(5, size=(5, 2)),
# bool doesn't work with numexpr but works elsewhere
- DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5),
+ np.array([True, False, True, False, True], dtype=np.bool_),
],
)
def test_frame_pos(self, lhs, engine, parser):
+ lhs = DataFrame(lhs)
expr = "+lhs"
expect = lhs
@@ -540,14 +541,15 @@ def test_frame_pos(self, lhs, engine, parser):
"lhs",
[
# Float
- Series(np.random.default_rng(2).standard_normal(5)),
+ np.random.default_rng(2).standard_normal(5),
# Int
- Series(np.random.default_rng(2).integers(5, size=5)),
+ np.random.default_rng(2).integers(5, size=5),
# bool doesn't work with numexpr but works elsewhere
- Series(np.random.default_rng(2).standard_normal(5) > 0.5),
+ np.array([True, False, True, False, True], dtype=np.bool_),
],
)
def test_series_pos(self, lhs, engine, parser):
+ lhs = Series(lhs)
expr = "+lhs"
expect = lhs
diff --git a/pandas/tests/copy_view/index/test_datetimeindex.py b/pandas/tests/copy_view/index/test_datetimeindex.py
index b023297c9549d..5dd1f45a94ff3 100644
--- a/pandas/tests/copy_view/index/test_datetimeindex.py
+++ b/pandas/tests/copy_view/index/test_datetimeindex.py
@@ -13,17 +13,11 @@
)
-@pytest.mark.parametrize(
- "cons",
- [
- lambda x: DatetimeIndex(x),
- lambda x: DatetimeIndex(DatetimeIndex(x)),
- ],
-)
-def test_datetimeindex(using_copy_on_write, cons):
+@pytest.mark.parametrize("box", [lambda x: x, DatetimeIndex])
+def test_datetimeindex(using_copy_on_write, box):
dt = date_range("2019-12-31", periods=3, freq="D")
ser = Series(dt)
- idx = cons(ser)
+ idx = box(DatetimeIndex(ser))
expected = idx.copy(deep=True)
ser.iloc[0] = Timestamp("2020-12-31")
if using_copy_on_write:
diff --git a/pandas/tests/copy_view/index/test_periodindex.py b/pandas/tests/copy_view/index/test_periodindex.py
index b80ce1d3d838f..753304a1a8963 100644
--- a/pandas/tests/copy_view/index/test_periodindex.py
+++ b/pandas/tests/copy_view/index/test_periodindex.py
@@ -13,17 +13,11 @@
)
-@pytest.mark.parametrize(
- "cons",
- [
- lambda x: PeriodIndex(x),
- lambda x: PeriodIndex(PeriodIndex(x)),
- ],
-)
-def test_periodindex(using_copy_on_write, cons):
+@pytest.mark.parametrize("box", [lambda x: x, PeriodIndex])
+def test_periodindex(using_copy_on_write, box):
dt = period_range("2019-12-31", periods=3, freq="D")
ser = Series(dt)
- idx = cons(ser)
+ idx = box(PeriodIndex(ser))
expected = idx.copy(deep=True)
ser.iloc[0] = Period("2020-12-31")
if using_copy_on_write:
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 5eeab778c184c..f1f5cb1620345 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1078,15 +1078,15 @@ def test_integers(self):
@pytest.mark.parametrize(
"arr, skipna",
[
- (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), False),
- (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), True),
- (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), False),
- (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), True),
+ ([1, 2, np.nan, np.nan, 3], False),
+ ([1, 2, np.nan, np.nan, 3], True),
+ ([1, 2, 3, np.int64(4), np.int32(5), np.nan], False),
+ ([1, 2, 3, np.int64(4), np.int32(5), np.nan], True),
],
)
def test_integer_na(self, arr, skipna):
# GH 27392
- result = lib.infer_dtype(arr, skipna=skipna)
+ result = lib.infer_dtype(np.array(arr, dtype="O"), skipna=skipna)
expected = "integer" if skipna else "integer-na"
assert result == expected
@@ -1287,13 +1287,13 @@ def test_infer_dtype_mixed_integer(self):
@pytest.mark.parametrize(
"arr",
[
- np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]),
- np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]),
- np.array([datetime(2011, 1, 1), Timestamp("2011-01-02")]),
+ [Timestamp("2011-01-01"), Timestamp("2011-01-02")],
+ [datetime(2011, 1, 1), datetime(2012, 2, 1)],
+ [datetime(2011, 1, 1), Timestamp("2011-01-02")],
],
)
def test_infer_dtype_datetime(self, arr):
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
+ assert lib.infer_dtype(np.array(arr), skipna=True) == "datetime"
@pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
@pytest.mark.parametrize(
@@ -1902,14 +1902,15 @@ def test_is_scalar_numpy_array_scalars(self):
@pytest.mark.parametrize(
"zerodim",
[
- np.array(1),
- np.array("foobar"),
- np.array(np.datetime64("2014-01-01")),
- np.array(np.timedelta64(1, "h")),
- np.array(np.datetime64("NaT")),
+ 1,
+ "foobar",
+ np.datetime64("2014-01-01"),
+ np.timedelta64(1, "h"),
+ np.datetime64("NaT"),
],
)
def test_is_scalar_numpy_zerodim_arrays(self, zerodim):
+ zerodim = np.array(zerodim)
assert not is_scalar(zerodim)
assert is_scalar(lib.item_from_zerodim(zerodim))
diff --git a/pandas/tests/frame/indexing/test_get.py b/pandas/tests/frame/indexing/test_get.py
index 5f2651eec683c..75bad0ec1f159 100644
--- a/pandas/tests/frame/indexing/test_get.py
+++ b/pandas/tests/frame/indexing/test_get.py
@@ -15,13 +15,13 @@ def test_get(self, float_frame):
)
@pytest.mark.parametrize(
- "df",
+ "columns, index",
[
- DataFrame(),
- DataFrame(columns=list("AB")),
- DataFrame(columns=list("AB"), index=range(3)),
+ [None, None],
+ [list("AB"), None],
+ [list("AB"), range(3)],
],
)
- def test_get_none(self, df):
+ def test_get_none(self, columns, index):
# see gh-5652
- assert df.get(None) is None
+ assert DataFrame(columns=columns, index=index).get(None) is None
diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py
index 06cd51b43a0aa..a3ae3991522c2 100644
--- a/pandas/tests/frame/methods/test_drop.py
+++ b/pandas/tests/frame/methods/test_drop.py
@@ -232,15 +232,13 @@ def test_drop_api_equivalence(self):
with pytest.raises(ValueError, match=msg):
df.drop(axis=1)
- data = [[1, 2, 3], [1, 2, 3]]
-
@pytest.mark.parametrize(
"actual",
[
- DataFrame(data=data, index=["a", "a"]),
- DataFrame(data=data, index=["a", "b"]),
- DataFrame(data=data, index=["a", "b"]).set_index([0, 1]),
- DataFrame(data=data, index=["a", "a"]).set_index([0, 1]),
+ DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "a"]),
+ DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "b"]),
+ DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "b"]).set_index([0, 1]),
+ DataFrame([[1, 2, 3], [1, 2, 3]], index=["a", "a"]).set_index([0, 1]),
],
)
def test_raise_on_drop_duplicate_index(self, actual):
diff --git a/pandas/tests/frame/methods/test_filter.py b/pandas/tests/frame/methods/test_filter.py
index 382615aaef627..dc84e2adf1239 100644
--- a/pandas/tests/frame/methods/test_filter.py
+++ b/pandas/tests/frame/methods/test_filter.py
@@ -98,15 +98,16 @@ def test_filter_regex_search(self, float_frame):
tm.assert_frame_equal(result, exp)
@pytest.mark.parametrize(
- "name,expected",
+ "name,expected_data",
[
- ("a", DataFrame({"a": [1, 2]})),
- ("あ", DataFrame({"あ": [3, 4]})),
+ ("a", {"a": [1, 2]}),
+ ("あ", {"あ": [3, 4]}),
],
)
- def test_filter_unicode(self, name, expected):
+ def test_filter_unicode(self, name, expected_data):
# GH13101
df = DataFrame({"a": [1, 2], "あ": [3, 4]})
+ expected = DataFrame(expected_data)
tm.assert_frame_equal(df.filter(like=name), expected)
tm.assert_frame_equal(df.filter(regex=name), expected)
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index 2a889efe79064..da6d69f36f900 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -1219,13 +1219,7 @@ def test_reindex_empty_frame(self, kwargs):
expected = DataFrame({"a": [np.nan] * 3}, index=idx, dtype=object)
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize(
- "src_idx",
- [
- Index([]),
- CategoricalIndex([]),
- ],
- )
+ @pytest.mark.parametrize("src_idx", [Index, CategoricalIndex])
@pytest.mark.parametrize(
"cat_idx",
[
@@ -1240,7 +1234,7 @@ def test_reindex_empty_frame(self, kwargs):
],
)
def test_reindex_empty(self, src_idx, cat_idx):
- df = DataFrame(columns=src_idx, index=["K"], dtype="f8")
+ df = DataFrame(columns=src_idx([]), index=["K"], dtype="f8")
result = df.reindex(columns=cat_idx)
expected = DataFrame(index=["K"], columns=cat_idx, dtype="f8")
@@ -1281,36 +1275,14 @@ def test_reindex_datetimelike_to_object(self, dtype):
assert res.iloc[-1, 1] is fv
tm.assert_frame_equal(res, expected)
- @pytest.mark.parametrize(
- "index_df,index_res,index_exp",
- [
- (
- CategoricalIndex([], categories=["A"]),
- Index(["A"]),
- Index(["A"]),
- ),
- (
- CategoricalIndex([], categories=["A"]),
- Index(["B"]),
- Index(["B"]),
- ),
- (
- CategoricalIndex([], categories=["A"]),
- CategoricalIndex(["A"]),
- CategoricalIndex(["A"]),
- ),
- (
- CategoricalIndex([], categories=["A"]),
- CategoricalIndex(["B"]),
- CategoricalIndex(["B"]),
- ),
- ],
- )
- def test_reindex_not_category(self, index_df, index_res, index_exp):
+ @pytest.mark.parametrize("klass", [Index, CategoricalIndex])
+ @pytest.mark.parametrize("data", ["A", "B"])
+ def test_reindex_not_category(self, klass, data):
# GH#28690
- df = DataFrame(index=index_df)
- result = df.reindex(index=index_res)
- expected = DataFrame(index=index_exp)
+ df = DataFrame(index=CategoricalIndex([], categories=["A"]))
+ idx = klass([data])
+ result = df.reindex(index=idx)
+ expected = DataFrame(index=idx)
tm.assert_frame_equal(result, expected)
def test_invalid_method(self):
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index d44de380d243a..6d52bf161f4fa 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -234,16 +234,9 @@ def test_empty_constructor(self, constructor):
assert len(result.columns) == 0
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize(
- "constructor",
- [
- lambda: DataFrame({}),
- lambda: DataFrame(data={}),
- ],
- )
- def test_empty_constructor_object_index(self, constructor):
+ def test_empty_constructor_object_index(self):
expected = DataFrame(index=RangeIndex(0), columns=RangeIndex(0))
- result = constructor()
+ result = DataFrame({})
assert len(result.index) == 0
assert len(result.columns) == 0
tm.assert_frame_equal(result, expected, check_index_type=True)
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 90524861ce311..1d8f50668cee2 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -1217,16 +1217,16 @@ def test_stack_preserve_categorical_dtype_values(self, future_stack):
)
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")
@pytest.mark.parametrize(
- "index, columns",
+ "index",
[
- ([0, 0, 1, 1], MultiIndex.from_product([[1, 2], ["a", "b"]])),
- ([0, 0, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])),
- ([0, 1, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])),
+ [0, 0, 1, 1],
+ [0, 0, 2, 3],
+ [0, 1, 2, 3],
],
)
- def test_stack_multi_columns_non_unique_index(self, index, columns, future_stack):
+ def test_stack_multi_columns_non_unique_index(self, index, future_stack):
# GH-28301
-
+ columns = MultiIndex.from_product([[1, 2], ["a", "b"]])
df = DataFrame(index=index, columns=columns).fillna(1)
stacked = df.stack(future_stack=future_stack)
new_index = MultiIndex.from_tuples(stacked.index.to_numpy())
@@ -1720,11 +1720,10 @@ def test_stack(self, multiindex_year_month_day_dataframe_random_data, future_sta
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
- "idx, columns, exp_idx",
+ "idx, exp_idx",
[
[
list("abab"),
- ["1st", "2nd", "1st"],
MultiIndex(
levels=[["a", "b"], ["1st", "2nd"]],
codes=[np.tile(np.arange(2).repeat(3), 2), np.tile([0, 1, 0], 4)],
@@ -1732,7 +1731,6 @@ def test_stack(self, multiindex_year_month_day_dataframe_random_data, future_sta
],
[
MultiIndex.from_tuples((("a", 2), ("b", 1), ("a", 1), ("b", 2))),
- ["1st", "2nd", "1st"],
MultiIndex(
levels=[["a", "b"], [1, 2], ["1st", "2nd"]],
codes=[
@@ -1744,12 +1742,12 @@ def test_stack(self, multiindex_year_month_day_dataframe_random_data, future_sta
],
],
)
- def test_stack_duplicate_index(self, idx, columns, exp_idx, future_stack):
+ def test_stack_duplicate_index(self, idx, exp_idx, future_stack):
# GH10417
df = DataFrame(
np.arange(12).reshape(4, 3),
index=idx,
- columns=columns,
+ columns=["1st", "2nd", "1st"],
)
if future_stack:
msg = "Columns with duplicate values are not supported in stack"
diff --git a/pandas/tests/frame/test_unary.py b/pandas/tests/frame/test_unary.py
index 850c92013694f..e89175ceff0c1 100644
--- a/pandas/tests/frame/test_unary.py
+++ b/pandas/tests/frame/test_unary.py
@@ -13,17 +13,16 @@ class TestDataFrameUnaryOperators:
# __pos__, __neg__, __invert__
@pytest.mark.parametrize(
- "df,expected",
+ "df_data,expected_data",
[
- (pd.DataFrame({"a": [-1, 1]}), pd.DataFrame({"a": [1, -1]})),
- (pd.DataFrame({"a": [False, True]}), pd.DataFrame({"a": [True, False]})),
- (
- pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
- pd.DataFrame({"a": pd.Series(pd.to_timedelta([1, -1]))}),
- ),
+ ([-1, 1], [1, -1]),
+ ([False, True], [True, False]),
+ (pd.to_timedelta([-1, 1]), pd.to_timedelta([1, -1])),
],
)
- def test_neg_numeric(self, df, expected):
+ def test_neg_numeric(self, df_data, expected_data):
+ df = pd.DataFrame({"a": df_data})
+ expected = pd.DataFrame({"a": expected_data})
tm.assert_frame_equal(-df, expected)
tm.assert_series_equal(-df["a"], expected["a"])
@@ -42,13 +41,14 @@ def test_neg_object(self, df, expected):
tm.assert_series_equal(-df["a"], expected["a"])
@pytest.mark.parametrize(
- "df",
+ "df_data",
[
- pd.DataFrame({"a": ["a", "b"]}),
- pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])}),
+ ["a", "b"],
+ pd.to_datetime(["2017-01-22", "1970-01-01"]),
],
)
- def test_neg_raises(self, df, using_infer_string):
+ def test_neg_raises(self, df_data, using_infer_string):
+ df = pd.DataFrame({"a": df_data})
msg = (
"bad operand type for unary -: 'str'|"
r"bad operand type for unary -: 'DatetimeArray'"
@@ -102,44 +102,36 @@ def test_invert_empty_not_input(self):
assert df is not result
@pytest.mark.parametrize(
- "df",
+ "df_data",
[
- pd.DataFrame({"a": [-1, 1]}),
- pd.DataFrame({"a": [False, True]}),
- pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
+ [-1, 1],
+ [False, True],
+ pd.to_timedelta([-1, 1]),
],
)
- def test_pos_numeric(self, df):
+ def test_pos_numeric(self, df_data):
# GH#16073
+ df = pd.DataFrame({"a": df_data})
tm.assert_frame_equal(+df, df)
tm.assert_series_equal(+df["a"], df["a"])
@pytest.mark.parametrize(
- "df",
+ "df_data",
[
- pd.DataFrame({"a": np.array([-1, 2], dtype=object)}),
- pd.DataFrame({"a": [Decimal("-1.0"), Decimal("2.0")]}),
+ np.array([-1, 2], dtype=object),
+ [Decimal("-1.0"), Decimal("2.0")],
],
)
- def test_pos_object(self, df):
+ def test_pos_object(self, df_data):
# GH#21380
+ df = pd.DataFrame({"a": df_data})
tm.assert_frame_equal(+df, df)
tm.assert_series_equal(+df["a"], df["a"])
- @pytest.mark.parametrize(
- "df",
- [
- pytest.param(
- pd.DataFrame({"a": ["a", "b"]}),
- # filterwarnings removable once min numpy version is 1.25
- marks=[
- pytest.mark.filterwarnings("ignore:Applying:DeprecationWarning")
- ],
- ),
- ],
- )
- def test_pos_object_raises(self, df):
+ @pytest.mark.filterwarnings("ignore:Applying:DeprecationWarning")
+ def test_pos_object_raises(self):
# GH#21380
+ df = pd.DataFrame({"a": ["a", "b"]})
if np_version_gte1p25:
with pytest.raises(
TypeError, match=r"^bad operand type for unary \+: \'str\'$"
@@ -148,10 +140,8 @@ def test_pos_object_raises(self, df):
else:
tm.assert_series_equal(+df["a"], df["a"])
- @pytest.mark.parametrize(
- "df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
- )
- def test_pos_raises(self, df):
+ def test_pos_raises(self):
+ df = pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})
msg = r"bad operand type for unary \+: 'DatetimeArray'"
with pytest.raises(TypeError, match=msg):
(+df)
diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py
index f54db07824daf..07f76810cbfc8 100644
--- a/pandas/tests/generic/test_duplicate_labels.py
+++ b/pandas/tests/generic/test_duplicate_labels.py
@@ -45,12 +45,11 @@ def test_preserved_series(self, func):
s = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
assert func(s).flags.allows_duplicate_labels is False
- @pytest.mark.parametrize(
- "other", [pd.Series(0, index=["a", "b", "c"]), pd.Series(0, index=["a", "b"])]
- )
+ @pytest.mark.parametrize("index", [["a", "b", "c"], ["a", "b"]])
# TODO: frame
@not_implemented
- def test_align(self, other):
+ def test_align(self, index):
+ other = pd.Series(0, index=index)
s = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
a, b = s.align(other)
assert a.flags.allows_duplicate_labels is False
@@ -298,23 +297,15 @@ def test_getitem_raises(self, getter, target):
with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
getter(target)
- @pytest.mark.parametrize(
- "objs, kwargs",
- [
- (
- [
- pd.Series(1, index=[0, 1], name="a"),
- pd.Series(2, index=[0, 1], name="a"),
- ],
- {"axis": 1},
- )
- ],
- )
- def test_concat_raises(self, objs, kwargs):
+ def test_concat_raises(self):
+ objs = [
+ pd.Series(1, index=[0, 1], name="a"),
+ pd.Series(2, index=[0, 1], name="a"),
+ ]
objs = [x.set_flags(allows_duplicate_labels=False) for x in objs]
msg = "Index has duplicates."
with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
- pd.concat(objs, **kwargs)
+ pd.concat(objs, axis=1)
@not_implemented
def test_merge_raises(self):
diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py
index 0596193c137e1..f5818d95020aa 100644
--- a/pandas/tests/groupby/aggregate/test_other.py
+++ b/pandas/tests/groupby/aggregate/test_other.py
@@ -540,46 +540,44 @@ def test_sum_uint64_overflow():
@pytest.mark.parametrize(
- "structure, expected",
+ "structure, cast_as",
[
- (tuple, DataFrame({"C": {(1, 1): (1, 1, 1), (3, 4): (3, 4, 4)}})),
- (list, DataFrame({"C": {(1, 1): [1, 1, 1], (3, 4): [3, 4, 4]}})),
- (
- lambda x: tuple(x),
- DataFrame({"C": {(1, 1): (1, 1, 1), (3, 4): (3, 4, 4)}}),
- ),
- (
- lambda x: list(x),
- DataFrame({"C": {(1, 1): [1, 1, 1], (3, 4): [3, 4, 4]}}),
- ),
+ (tuple, tuple),
+ (list, list),
+ (lambda x: tuple(x), tuple),
+ (lambda x: list(x), list),
],
)
-def test_agg_structs_dataframe(structure, expected):
+def test_agg_structs_dataframe(structure, cast_as):
df = DataFrame(
{"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]}
)
result = df.groupby(["A", "B"]).aggregate(structure)
+ expected = DataFrame(
+ {"C": {(1, 1): cast_as([1, 1, 1]), (3, 4): cast_as([3, 4, 4])}}
+ )
expected.index.names = ["A", "B"]
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
- "structure, expected",
+ "structure, cast_as",
[
- (tuple, Series([(1, 1, 1), (3, 4, 4)], index=[1, 3], name="C")),
- (list, Series([[1, 1, 1], [3, 4, 4]], index=[1, 3], name="C")),
- (lambda x: tuple(x), Series([(1, 1, 1), (3, 4, 4)], index=[1, 3], name="C")),
- (lambda x: list(x), Series([[1, 1, 1], [3, 4, 4]], index=[1, 3], name="C")),
+ (tuple, tuple),
+ (list, list),
+ (lambda x: tuple(x), tuple),
+ (lambda x: list(x), list),
],
)
-def test_agg_structs_series(structure, expected):
+def test_agg_structs_series(structure, cast_as):
# Issue #18079
df = DataFrame(
{"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]}
)
result = df.groupby("A")["C"].aggregate(structure)
+ expected = Series([cast_as([1, 1, 1]), cast_as([3, 4, 4])], index=[1, 3], name="C")
expected.index.name = "A"
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index ac5374597585a..07d52308e308a 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -41,24 +41,27 @@ def test_mgr_locs_updated(func):
"binner,closed,expected",
[
(
- np.array([0, 3, 6, 9], dtype=np.int64),
+ [0, 3, 6, 9],
"left",
- np.array([2, 5, 6], dtype=np.int64),
+ [2, 5, 6],
),
(
- np.array([0, 3, 6, 9], dtype=np.int64),
+ [0, 3, 6, 9],
"right",
- np.array([3, 6, 6], dtype=np.int64),
+ [3, 6, 6],
),
- (np.array([0, 3, 6], dtype=np.int64), "left", np.array([2, 5], dtype=np.int64)),
+ ([0, 3, 6], "left", [2, 5]),
(
- np.array([0, 3, 6], dtype=np.int64),
+ [0, 3, 6],
"right",
- np.array([3, 6], dtype=np.int64),
+ [3, 6],
),
],
)
def test_generate_bins(binner, closed, expected):
values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64)
- result = lib.generate_bins_dt64(values, binner, closed=closed)
+ result = lib.generate_bins_dt64(
+ values, np.array(binner, dtype=np.int64), closed=closed
+ )
+ expected = np.array(expected, dtype=np.int64)
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 038f59f8ea80f..14c5c21d41772 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -350,12 +350,9 @@ def test_basic_regression():
grouped.mean()
-@pytest.mark.parametrize(
- "dtype", ["float64", "float32", "int64", "int32", "int16", "int8"]
-)
-def test_with_na_groups(dtype):
+def test_with_na_groups(any_real_numpy_dtype):
index = Index(np.arange(10))
- values = Series(np.ones(10), index, dtype=dtype)
+ values = Series(np.ones(10), index, dtype=any_real_numpy_dtype)
labels = Series(
[np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"],
index=index,
| Moves similar parametrization setup to test bodies | https://api.github.com/repos/pandas-dev/pandas/pulls/56737 | 2024-01-04T22:52:46Z | 2024-01-06T15:11:31Z | 2024-01-06T15:11:31Z | 2024-01-08T00:06:11Z |
#56696 Added Cheatsheet Section and cheatsheet link to pandas home page | diff --git a/doc/source/_static/cheatsheet.jpg b/doc/source/_static/cheatsheet.jpg
new file mode 100644
index 0000000000000..147fce4536971
Binary files /dev/null and b/doc/source/_static/cheatsheet.jpg differ
diff --git a/doc/source/getting_started/index.rst b/doc/source/getting_started/index.rst
index d9cb1de14aded..286e035bf45e3 100644
--- a/doc/source/getting_started/index.rst
+++ b/doc/source/getting_started/index.rst
@@ -646,6 +646,23 @@ the pandas-equivalent operations compared to software you already know:
Learn more
+CheatSheet
+--------------
+
+If you're looking for a quick overview of Pandas, check out the cheat sheet! It's a handy reference that provides a succinct guide for manipulating data with Pandas. You can access the cheat sheet.
+
+`Cheatsheet <https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf>`__
+
+.. grid:: 1 2 2 2
+ :gutter: 4
+ :class-container: sd-text-center sd-d-inline-flex
+
+ .. grid-item-card::
+ :img-top: ../_static/cheatsheet.jpg
+ :columns: 12 6 6 6
+ :class-card: comparison-card
+ :shadow: md
+
Tutorials
---------
| - [x] closes #56696 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
## This is space where i wanted to add the link to the cheatsheet and small cheatsheet section

## This is the section i have added and changed in the "pandas/blob/main/doc/source/getting_started/index.rst"

| https://api.github.com/repos/pandas-dev/pandas/pulls/56736 | 2024-01-04T20:17:46Z | 2024-01-29T05:08:55Z | null | 2024-01-29T05:08:55Z |
fix: add pytest-qt deps to dockerfile | diff --git a/Dockerfile b/Dockerfile
index 7230dcab20f6e..c697f0c1c66c7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -5,7 +5,8 @@ RUN apt-get update && apt-get -y upgrade
RUN apt-get install -y build-essential
# hdf5 needed for pytables installation
-RUN apt-get install -y libhdf5-dev
+# libgles2-mesa needed for pytest-qt
+RUN apt-get install -y libhdf5-dev libgles2-mesa-dev
RUN python -m pip install --upgrade pip
RUN python -m pip install \
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56731 | 2024-01-04T04:21:10Z | 2024-01-04T16:13:43Z | 2024-01-04T16:13:43Z | 2024-01-04T16:13:50Z |
Backport PR #56543 on branch 2.2.x (DOC: Update docstring for read_excel) | diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 6148086452d54..b3ad23e0d4104 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -3471,20 +3471,15 @@ saving a ``DataFrame`` to Excel. Generally the semantics are
similar to working with :ref:`csv<io.read_csv_table>` data.
See the :ref:`cookbook<cookbook.excel>` for some advanced strategies.
-.. warning::
-
- The `xlrd <https://xlrd.readthedocs.io/en/latest/>`__ package is now only for reading
- old-style ``.xls`` files.
+.. note::
- Before pandas 1.3.0, the default argument ``engine=None`` to :func:`~pandas.read_excel`
- would result in using the ``xlrd`` engine in many cases, including new
- Excel 2007+ (``.xlsx``) files. pandas will now default to using the
- `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__ engine.
+ When ``engine=None``, the following logic will be used to determine the engine:
- It is strongly encouraged to install ``openpyxl`` to read Excel 2007+
- (``.xlsx``) files.
- **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
- This is no longer supported, switch to using ``openpyxl`` instead.
+ - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
+ then `odf <https://pypi.org/project/odfpy/>`_ will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used.
+ - Otherwise if ``path_or_buffer`` is in xlsb format, ``pyxlsb`` will be used.
+ - Otherwise ``openpyxl`` will be used.
.. _io.excel_reader:
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index bce890c6f73b0..786f719337b84 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -160,36 +160,24 @@
If converters are specified, they will be applied INSTEAD
of dtype conversion.
If you use ``None``, it will infer the dtype of each column based on the data.
-engine : str, default None
+engine : {{'openpyxl', 'calamine', 'odf', 'pyxlsb', 'xlrd'}}, default None
If io is not a buffer or path, this must be set to identify io.
- Supported engines: "xlrd", "openpyxl", "odf", "pyxlsb", "calamine".
Engine compatibility :
- - ``xlr`` supports old-style Excel files (.xls).
- ``openpyxl`` supports newer Excel file formats.
- - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
- - ``pyxlsb`` supports Binary Excel files.
- ``calamine`` supports Excel (.xls, .xlsx, .xlsm, .xlsb)
and OpenDocument (.ods) file formats.
+ - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
+ - ``pyxlsb`` supports Binary Excel files.
+ - ``xlrd`` supports old-style Excel files (.xls).
- .. versionchanged:: 1.2.0
- The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
- now only supports old-style ``.xls`` files.
- When ``engine=None``, the following logic will be
- used to determine the engine:
-
- - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
- then `odf <https://pypi.org/project/odfpy/>`_ will be used.
- - Otherwise if ``path_or_buffer`` is an xls format,
- ``xlrd`` will be used.
- - Otherwise if ``path_or_buffer`` is in xlsb format,
- ``pyxlsb`` will be used.
-
- .. versionadded:: 1.3.0
- - Otherwise ``openpyxl`` will be used.
-
- .. versionchanged:: 1.3.0
+ When ``engine=None``, the following logic will be used to determine the engine:
+ - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
+ then `odf <https://pypi.org/project/odfpy/>`_ will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used.
+ - Otherwise if ``path_or_buffer`` is in xlsb format, ``pyxlsb`` will be used.
+ - Otherwise ``openpyxl`` will be used.
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
either be integers or column labels, values are functions that take one
| Backport PR #56543: DOC: Update docstring for read_excel | https://api.github.com/repos/pandas-dev/pandas/pulls/56730 | 2024-01-04T03:30:29Z | 2024-01-04T08:21:26Z | 2024-01-04T08:21:26Z | 2024-01-04T08:21:27Z |
TST/CLN: Reuse more fixtures | diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py
index 65e234e799353..f6a4396ca5be0 100644
--- a/pandas/tests/base/test_misc.py
+++ b/pandas/tests/base/test_misc.py
@@ -17,7 +17,6 @@
Index,
Series,
)
-import pandas._testing as tm
def test_isnull_notnull_docstrings():
@@ -130,9 +129,13 @@ def test_memory_usage_components_series(series_with_simple_index):
assert total_usage == non_index_usage + index_usage
-@pytest.mark.parametrize("dtype", tm.NARROW_NP_DTYPES)
-def test_memory_usage_components_narrow_series(dtype):
- series = Series(range(5), dtype=dtype, index=[f"i-{i}" for i in range(5)], name="a")
+def test_memory_usage_components_narrow_series(any_real_numpy_dtype):
+ series = Series(
+ range(5),
+ dtype=any_real_numpy_dtype,
+ index=[f"i-{i}" for i in range(5)],
+ name="a",
+ )
total_usage = series.memory_usage(index=True)
non_index_usage = series.memory_usage(index=False)
index_usage = series.index.memory_usage()
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index f36ddff223a9a..f9c6939654ea1 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -75,8 +75,7 @@ class TestiLocBaseIndependent:
np.asarray([0, 1, 2]),
],
)
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_iloc_setitem_fullcol_categorical(self, indexer, key):
+ def test_iloc_setitem_fullcol_categorical(self, indexer_li, key):
frame = DataFrame({0: range(3)}, dtype=object)
cat = Categorical(["alpha", "beta", "gamma"])
@@ -86,7 +85,7 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key):
df = frame.copy()
orig_vals = df.values
- indexer(df)[key, 0] = cat
+ indexer_li(df)[key, 0] = cat
expected = DataFrame({0: cat}).astype(object)
assert np.shares_memory(df[0].values, orig_vals)
@@ -102,7 +101,7 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key):
# we retain the object dtype.
frame = DataFrame({0: np.array([0, 1, 2], dtype=object), 1: range(3)})
df = frame.copy()
- indexer(df)[key, 0] = cat
+ indexer_li(df)[key, 0] = cat
expected = DataFrame({0: Series(cat.astype(object), dtype=object), 1: range(3)})
tm.assert_frame_equal(df, expected)
@@ -985,8 +984,7 @@ def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self):
with pytest.raises(ValueError, match=msg):
obj.iloc[nd3] = 0
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_iloc_getitem_read_only_values(self, indexer):
+ def test_iloc_getitem_read_only_values(self, indexer_li):
# GH#10043 this is fundamentally a test for iloc, but test loc while
# we're here
rw_array = np.eye(10)
@@ -996,10 +994,12 @@ def test_iloc_getitem_read_only_values(self, indexer):
ro_array.setflags(write=False)
ro_df = DataFrame(ro_array)
- tm.assert_frame_equal(indexer(rw_df)[[1, 2, 3]], indexer(ro_df)[[1, 2, 3]])
- tm.assert_frame_equal(indexer(rw_df)[[1]], indexer(ro_df)[[1]])
- tm.assert_series_equal(indexer(rw_df)[1], indexer(ro_df)[1])
- tm.assert_frame_equal(indexer(rw_df)[1:3], indexer(ro_df)[1:3])
+ tm.assert_frame_equal(
+ indexer_li(rw_df)[[1, 2, 3]], indexer_li(ro_df)[[1, 2, 3]]
+ )
+ tm.assert_frame_equal(indexer_li(rw_df)[[1]], indexer_li(ro_df)[[1]])
+ tm.assert_series_equal(indexer_li(rw_df)[1], indexer_li(ro_df)[1])
+ tm.assert_frame_equal(indexer_li(rw_df)[1:3], indexer_li(ro_df)[1:3])
def test_iloc_getitem_readonly_key(self):
# GH#17192 iloc with read-only array raising TypeError
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index ce02e752fb90b..70fd0b02cc79d 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -132,15 +132,12 @@ def test_dtype_with_converters(all_parsers):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize(
- "dtype", list(np.typecodes["AllInteger"] + np.typecodes["Float"])
-)
-def test_numeric_dtype(all_parsers, dtype):
+def test_numeric_dtype(all_parsers, any_real_numpy_dtype):
data = "0\n1"
parser = all_parsers
- expected = DataFrame([0, 1], dtype=dtype)
+ expected = DataFrame([0, 1], dtype=any_real_numpy_dtype)
- result = parser.read_csv(StringIO(data), header=None, dtype=dtype)
+ result = parser.read_csv(StringIO(data), header=None, dtype=any_real_numpy_dtype)
tm.assert_frame_equal(expected, result)
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index fcb5b65e59402..4cdd50d70d078 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -1417,13 +1417,10 @@ def test_mode_empty(self, dropna, expected):
(False, [1, 1, 1, 2, 3, 3, 3], [1, 3]),
],
)
- @pytest.mark.parametrize(
- "dt", list(np.typecodes["AllInteger"] + np.typecodes["Float"])
- )
- def test_mode_numerical(self, dropna, data, expected, dt):
- s = Series(data, dtype=dt)
+ def test_mode_numerical(self, dropna, data, expected, any_real_numpy_dtype):
+ s = Series(data, dtype=any_real_numpy_dtype)
result = s.mode(dropna)
- expected = Series(expected, dtype=dt)
+ expected = Series(expected, dtype=any_real_numpy_dtype)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dropna, expected", [(True, [1.0]), (False, [1, np.nan])])
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 21a38c43f4294..3b37ffa7baa82 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1488,12 +1488,9 @@ def test_different(self, right_vals):
result = merge(left, right, on="A")
assert is_object_dtype(result.A.dtype)
- @pytest.mark.parametrize(
- "d1", [np.int64, np.int32, np.intc, np.int16, np.int8, np.uint8]
- )
@pytest.mark.parametrize("d2", [np.int64, np.float64, np.float32, np.float16])
- def test_join_multi_dtypes(self, d1, d2):
- dtype1 = np.dtype(d1)
+ def test_join_multi_dtypes(self, any_int_numpy_dtype, d2):
+ dtype1 = np.dtype(any_int_numpy_dtype)
dtype2 = np.dtype(d2)
left = DataFrame(
diff --git a/pandas/tests/scalar/timestamp/test_formats.py b/pandas/tests/scalar/timestamp/test_formats.py
index d7160597ea6d6..6a578b0a9eb09 100644
--- a/pandas/tests/scalar/timestamp/test_formats.py
+++ b/pandas/tests/scalar/timestamp/test_formats.py
@@ -88,9 +88,9 @@ def test_isoformat(ts, timespec, expected_iso):
class TestTimestampRendering:
- timezones = ["UTC", "Asia/Tokyo", "US/Eastern", "dateutil/US/Pacific"]
-
- @pytest.mark.parametrize("tz", timezones)
+ @pytest.mark.parametrize(
+ "tz", ["UTC", "Asia/Tokyo", "US/Eastern", "dateutil/US/Pacific"]
+ )
@pytest.mark.parametrize("freq", ["D", "M", "S", "N"])
@pytest.mark.parametrize(
"date", ["2014-03-07", "2014-01-01 09:00", "2014-01-01 00:00:00.000000001"]
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 46f55fff91e41..4d2cd2ba963fd 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -342,10 +342,9 @@ def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors):
with pytest.raises((ValueError, TypeError), match=msg):
ser.astype(float, errors=errors)
- @pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64])
- def test_astype_from_float_to_str(self, dtype):
+ def test_astype_from_float_to_str(self, any_float_dtype):
# https://github.com/pandas-dev/pandas/issues/36451
- ser = Series([0.1], dtype=dtype)
+ ser = Series([0.1], dtype=any_float_dtype)
result = ser.astype(str)
expected = Series(["0.1"], dtype=object)
tm.assert_series_equal(result, expected)
@@ -374,21 +373,19 @@ def test_astype(self, dtype):
assert as_typed.name == ser.name
@pytest.mark.parametrize("value", [np.nan, np.inf])
- @pytest.mark.parametrize("dtype", [np.int32, np.int64])
- def test_astype_cast_nan_inf_int(self, dtype, value):
+ def test_astype_cast_nan_inf_int(self, any_int_numpy_dtype, value):
# gh-14265: check NaN and inf raise error when converting to int
msg = "Cannot convert non-finite values \\(NA or inf\\) to integer"
ser = Series([value])
with pytest.raises(ValueError, match=msg):
- ser.astype(dtype)
+ ser.astype(any_int_numpy_dtype)
- @pytest.mark.parametrize("dtype", [int, np.int8, np.int64])
- def test_astype_cast_object_int_fail(self, dtype):
+ def test_astype_cast_object_int_fail(self, any_int_numpy_dtype):
arr = Series(["car", "house", "tree", "1"])
msg = r"invalid literal for int\(\) with base 10: 'car'"
with pytest.raises(ValueError, match=msg):
- arr.astype(dtype)
+ arr.astype(any_int_numpy_dtype)
def test_astype_float_to_uint_negatives_raise(
self, float_numpy_dtype, any_unsigned_int_numpy_dtype
diff --git a/pandas/tests/series/methods/test_compare.py b/pandas/tests/series/methods/test_compare.py
index fe2016a245ec7..304045e46702b 100644
--- a/pandas/tests/series/methods/test_compare.py
+++ b/pandas/tests/series/methods/test_compare.py
@@ -5,15 +5,14 @@
import pandas._testing as tm
-@pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"])
-def test_compare_axis(align_axis):
+def test_compare_axis(axis):
# GH#30429
s1 = pd.Series(["a", "b", "c"])
s2 = pd.Series(["x", "b", "z"])
- result = s1.compare(s2, align_axis=align_axis)
+ result = s1.compare(s2, align_axis=axis)
- if align_axis in (1, "columns"):
+ if axis in (1, "columns"):
indices = pd.Index([0, 2])
columns = pd.Index(["self", "other"])
expected = pd.DataFrame(
diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py
index a369145b4e884..bd60265582652 100644
--- a/pandas/tests/series/methods/test_cov_corr.py
+++ b/pandas/tests/series/methods/test_cov_corr.py
@@ -56,11 +56,10 @@ def test_cov_ddof(self, test_ddof, dtype):
class TestSeriesCorr:
- @pytest.mark.parametrize("dtype", ["float64", "Float64"])
- def test_corr(self, datetime_series, dtype):
+ def test_corr(self, datetime_series, any_float_dtype):
stats = pytest.importorskip("scipy.stats")
- datetime_series = datetime_series.astype(dtype)
+ datetime_series = datetime_series.astype(any_float_dtype)
# full overlap
tm.assert_almost_equal(datetime_series.corr(datetime_series), 1)
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 293259661cd9a..f38e4a622cffa 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -838,12 +838,11 @@ def test_fillna_categorical_raises(self):
ser.fillna(DataFrame({1: ["a"], 3: ["b"]}))
@pytest.mark.parametrize("dtype", [float, "float32", "float64"])
- @pytest.mark.parametrize("fill_type", tm.ALL_REAL_NUMPY_DTYPES)
@pytest.mark.parametrize("scalar", [True, False])
- def test_fillna_float_casting(self, dtype, fill_type, scalar):
+ def test_fillna_float_casting(self, dtype, any_real_numpy_dtype, scalar):
# GH-43424
ser = Series([np.nan, 1.2], dtype=dtype)
- fill_values = Series([2, 2], dtype=fill_type)
+ fill_values = Series([2, 2], dtype=any_real_numpy_dtype)
if scalar:
fill_values = fill_values.dtype.type(2)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 02cd7b77c9b7d..de0338b39d91a 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -1795,11 +1795,10 @@ def test_scipy_compat(self, arr):
exp[mask] = np.nan
tm.assert_almost_equal(result, exp)
- @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
- def test_basic(self, writable, dtype):
+ def test_basic(self, writable, any_int_numpy_dtype):
exp = np.array([1, 2], dtype=np.float64)
- data = np.array([1, 100], dtype=dtype)
+ data = np.array([1, 100], dtype=any_int_numpy_dtype)
data.setflags(write=writable)
ser = Series(data)
result = algos.rank(ser)
@@ -1836,8 +1835,7 @@ def test_no_mode(self):
exp = Series([], dtype=np.float64, index=Index([], dtype=int))
tm.assert_numpy_array_equal(algos.mode(np.array([])), exp.values)
- @pytest.mark.parametrize("dt", np.typecodes["AllInteger"] + np.typecodes["Float"])
- def test_mode_single(self, dt):
+ def test_mode_single(self, any_real_numpy_dtype):
# GH 15714
exp_single = [1]
data_single = [1]
@@ -1845,13 +1843,13 @@ def test_mode_single(self, dt):
exp_multi = [1]
data_multi = [1, 1]
- ser = Series(data_single, dtype=dt)
- exp = Series(exp_single, dtype=dt)
+ ser = Series(data_single, dtype=any_real_numpy_dtype)
+ exp = Series(exp_single, dtype=any_real_numpy_dtype)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
- ser = Series(data_multi, dtype=dt)
- exp = Series(exp_multi, dtype=dt)
+ ser = Series(data_multi, dtype=any_real_numpy_dtype)
+ exp = Series(exp_multi, dtype=any_real_numpy_dtype)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
@@ -1862,21 +1860,20 @@ def test_mode_obj_int(self):
exp = Series(["a", "b", "c"], dtype=object)
tm.assert_numpy_array_equal(algos.mode(exp.values), exp.values)
- @pytest.mark.parametrize("dt", np.typecodes["AllInteger"] + np.typecodes["Float"])
- def test_number_mode(self, dt):
+ def test_number_mode(self, any_real_numpy_dtype):
exp_single = [1]
data_single = [1] * 5 + [2] * 3
exp_multi = [1, 3]
data_multi = [1] * 5 + [2] * 3 + [3] * 5
- ser = Series(data_single, dtype=dt)
- exp = Series(exp_single, dtype=dt)
+ ser = Series(data_single, dtype=any_real_numpy_dtype)
+ exp = Series(exp_single, dtype=any_real_numpy_dtype)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
- ser = Series(data_multi, dtype=dt)
- exp = Series(exp_multi, dtype=dt)
+ ser = Series(data_multi, dtype=any_real_numpy_dtype)
+ exp = Series(exp_multi, dtype=any_real_numpy_dtype)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
diff --git a/pandas/tests/util/test_assert_extension_array_equal.py b/pandas/tests/util/test_assert_extension_array_equal.py
index 674e9307d8bb9..5d82ae9af0e95 100644
--- a/pandas/tests/util/test_assert_extension_array_equal.py
+++ b/pandas/tests/util/test_assert_extension_array_equal.py
@@ -108,11 +108,10 @@ def test_assert_extension_array_equal_non_extension_array(side):
tm.assert_extension_array_equal(*args)
-@pytest.mark.parametrize("right_dtype", ["Int32", "int64"])
-def test_assert_extension_array_equal_ignore_dtype_mismatch(right_dtype):
+def test_assert_extension_array_equal_ignore_dtype_mismatch(any_int_dtype):
# https://github.com/pandas-dev/pandas/issues/35715
left = array([1, 2, 3], dtype="Int64")
- right = array([1, 2, 3], dtype=right_dtype)
+ right = array([1, 2, 3], dtype=any_int_dtype)
tm.assert_extension_array_equal(left, right, check_dtype=False)
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index c4ffc197298f0..70efa4293c46d 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -106,12 +106,11 @@ def test_series_not_equal_metadata_mismatch(kwargs):
@pytest.mark.parametrize("data1,data2", [(0.12345, 0.12346), (0.1235, 0.1236)])
-@pytest.mark.parametrize("dtype", ["float32", "float64", "Float32"])
@pytest.mark.parametrize("decimals", [0, 1, 2, 3, 5, 10])
-def test_less_precise(data1, data2, dtype, decimals):
+def test_less_precise(data1, data2, any_float_dtype, decimals):
rtol = 10**-decimals
- s1 = Series([data1], dtype=dtype)
- s2 = Series([data2], dtype=dtype)
+ s1 = Series([data1], dtype=any_float_dtype)
+ s2 = Series([data2], dtype=any_float_dtype)
if decimals in (5, 10) or (decimals >= 3 and abs(data1 - data2) >= 0.0005):
msg = "Series values are different"
diff --git a/pandas/tests/window/test_rolling_functions.py b/pandas/tests/window/test_rolling_functions.py
index 5906ff52db098..f77a98ae9a7d9 100644
--- a/pandas/tests/window/test_rolling_functions.py
+++ b/pandas/tests/window/test_rolling_functions.py
@@ -471,20 +471,19 @@ def test_rolling_median_memory_error():
).median()
-@pytest.mark.parametrize(
- "data_type",
- [np.dtype(f"f{width}") for width in [4, 8]]
- + [np.dtype(f"{sign}{width}") for width in [1, 2, 4, 8] for sign in "ui"],
-)
-def test_rolling_min_max_numeric_types(data_type):
+def test_rolling_min_max_numeric_types(any_real_numpy_dtype):
# GH12373
# Just testing that these don't throw exceptions and that
# the return type is float64. Other tests will cover quantitative
# correctness
- result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).max()
+ result = (
+ DataFrame(np.arange(20, dtype=any_real_numpy_dtype)).rolling(window=5).max()
+ )
assert result.dtypes[0] == np.dtype("f8")
- result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).min()
+ result = (
+ DataFrame(np.arange(20, dtype=any_real_numpy_dtype)).rolling(window=5).min()
+ )
assert result.dtypes[0] == np.dtype("f8")
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56726 | 2024-01-04T00:37:34Z | 2024-01-04T19:52:12Z | 2024-01-04T19:52:12Z | 2024-01-04T22:52:55Z |
Backport PR #56721 on branch 2.2.x (DOC: Fixup read_csv docstring) | diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index a9b41b45aba2f..e26e7e7470461 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -396,7 +396,7 @@
- Callable, function with signature
as described in `pyarrow documentation
<https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html
- #pyarrow.csv.ParseOptions.invalid_row_handler>_` when ``engine='pyarrow'``
+ #pyarrow.csv.ParseOptions.invalid_row_handler>`_ when ``engine='pyarrow'``
delim_whitespace : bool, default False
Specifies whether or not whitespace (e.g. ``' '`` or ``'\\t'``) will be
| Backport PR #56721: DOC: Fixup read_csv docstring | https://api.github.com/repos/pandas-dev/pandas/pulls/56725 | 2024-01-03T23:31:50Z | 2024-01-03T23:33:36Z | 2024-01-03T23:33:36Z | 2024-01-03T23:33:37Z |
TST: Don't ignore tolerance for integer series | diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index d0f38c85868d4..3de982498e996 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -10,6 +10,7 @@
import numpy as np
+from pandas._libs import lib
from pandas._libs.missing import is_matching_na
from pandas._libs.sparse import SparseIndex
import pandas._libs.testing as _testing
@@ -698,9 +699,9 @@ def assert_extension_array_equal(
right,
check_dtype: bool | Literal["equiv"] = True,
index_values=None,
- check_exact: bool = False,
- rtol: float = 1.0e-5,
- atol: float = 1.0e-8,
+ check_exact: bool | lib.NoDefault = lib.no_default,
+ rtol: float | lib.NoDefault = lib.no_default,
+ atol: float | lib.NoDefault = lib.no_default,
obj: str = "ExtensionArray",
) -> None:
"""
@@ -715,7 +716,12 @@ def assert_extension_array_equal(
index_values : Index | numpy.ndarray, default None
Optional index (shared by both left and right), used in output.
check_exact : bool, default False
- Whether to compare number exactly. Only takes effect for float dtypes.
+ Whether to compare number exactly.
+
+ .. versionchanged:: 2.2.0
+
+ Defaults to True for integer dtypes if none of
+ ``check_exact``, ``rtol`` and ``atol`` are specified.
rtol : float, default 1e-5
Relative tolerance. Only used when check_exact is False.
atol : float, default 1e-8
@@ -739,6 +745,23 @@ def assert_extension_array_equal(
>>> b, c = a.array, a.array
>>> tm.assert_extension_array_equal(b, c)
"""
+ if (
+ check_exact is lib.no_default
+ and rtol is lib.no_default
+ and atol is lib.no_default
+ ):
+ check_exact = (
+ is_numeric_dtype(left.dtype)
+ and not is_float_dtype(left.dtype)
+ or is_numeric_dtype(right.dtype)
+ and not is_float_dtype(right.dtype)
+ )
+ elif check_exact is lib.no_default:
+ check_exact = False
+
+ rtol = rtol if rtol is not lib.no_default else 1.0e-5
+ atol = atol if atol is not lib.no_default else 1.0e-8
+
assert isinstance(left, ExtensionArray), "left is not an ExtensionArray"
assert isinstance(right, ExtensionArray), "right is not an ExtensionArray"
if check_dtype:
@@ -784,10 +807,7 @@ def assert_extension_array_equal(
left_valid = left[~left_na].to_numpy(dtype=object)
right_valid = right[~right_na].to_numpy(dtype=object)
- if check_exact or (
- (is_numeric_dtype(left.dtype) and not is_float_dtype(left.dtype))
- or (is_numeric_dtype(right.dtype) and not is_float_dtype(right.dtype))
- ):
+ if check_exact:
assert_numpy_array_equal(
left_valid, right_valid, obj=obj, index_values=index_values
)
@@ -811,14 +831,14 @@ def assert_series_equal(
check_index_type: bool | Literal["equiv"] = "equiv",
check_series_type: bool = True,
check_names: bool = True,
- check_exact: bool = False,
+ check_exact: bool | lib.NoDefault = lib.no_default,
check_datetimelike_compat: bool = False,
check_categorical: bool = True,
check_category_order: bool = True,
check_freq: bool = True,
check_flags: bool = True,
- rtol: float = 1.0e-5,
- atol: float = 1.0e-8,
+ rtol: float | lib.NoDefault = lib.no_default,
+ atol: float | lib.NoDefault = lib.no_default,
obj: str = "Series",
*,
check_index: bool = True,
@@ -841,7 +861,12 @@ def assert_series_equal(
check_names : bool, default True
Whether to check the Series and Index names attribute.
check_exact : bool, default False
- Whether to compare number exactly. Only takes effect for float dtypes.
+ Whether to compare number exactly.
+
+ .. versionchanged:: 2.2.0
+
+ Defaults to True for integer dtypes if none of
+ ``check_exact``, ``rtol`` and ``atol`` are specified.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
@@ -877,6 +902,22 @@ def assert_series_equal(
>>> tm.assert_series_equal(a, b)
"""
__tracebackhide__ = True
+ if (
+ check_exact is lib.no_default
+ and rtol is lib.no_default
+ and atol is lib.no_default
+ ):
+ check_exact = (
+ is_numeric_dtype(left.dtype)
+ and not is_float_dtype(left.dtype)
+ or is_numeric_dtype(right.dtype)
+ and not is_float_dtype(right.dtype)
+ )
+ elif check_exact is lib.no_default:
+ check_exact = False
+
+ rtol = rtol if rtol is not lib.no_default else 1.0e-5
+ atol = atol if atol is not lib.no_default else 1.0e-8
if not check_index and check_like:
raise ValueError("check_like must be False if check_index is False")
@@ -931,10 +972,7 @@ def assert_series_equal(
pass
else:
assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
- if check_exact or (
- (is_numeric_dtype(left.dtype) and not is_float_dtype(left.dtype))
- or (is_numeric_dtype(right.dtype) and not is_float_dtype(right.dtype))
- ):
+ if check_exact:
left_values = left._values
right_values = right._values
# Only check exact if dtype is numeric
@@ -1061,14 +1099,14 @@ def assert_frame_equal(
check_frame_type: bool = True,
check_names: bool = True,
by_blocks: bool = False,
- check_exact: bool = False,
+ check_exact: bool | lib.NoDefault = lib.no_default,
check_datetimelike_compat: bool = False,
check_categorical: bool = True,
check_like: bool = False,
check_freq: bool = True,
check_flags: bool = True,
- rtol: float = 1.0e-5,
- atol: float = 1.0e-8,
+ rtol: float | lib.NoDefault = lib.no_default,
+ atol: float | lib.NoDefault = lib.no_default,
obj: str = "DataFrame",
) -> None:
"""
@@ -1103,7 +1141,12 @@ def assert_frame_equal(
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
check_exact : bool, default False
- Whether to compare number exactly. Only takes effect for float dtypes.
+ Whether to compare number exactly.
+
+ .. versionchanged:: 2.2.0
+
+ Defaults to True for integer dtypes if none of
+ ``check_exact``, ``rtol`` and ``atol`` are specified.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
@@ -1158,6 +1201,9 @@ def assert_frame_equal(
>>> assert_frame_equal(df1, df2, check_dtype=False)
"""
__tracebackhide__ = True
+ _rtol = rtol if rtol is not lib.no_default else 1.0e-5
+ _atol = atol if atol is not lib.no_default else 1.0e-8
+ _check_exact = check_exact if check_exact is not lib.no_default else False
# instance validation
_check_isinstance(left, right, DataFrame)
@@ -1181,11 +1227,11 @@ def assert_frame_equal(
right.index,
exact=check_index_type,
check_names=check_names,
- check_exact=check_exact,
+ check_exact=_check_exact,
check_categorical=check_categorical,
check_order=not check_like,
- rtol=rtol,
- atol=atol,
+ rtol=_rtol,
+ atol=_atol,
obj=f"{obj}.index",
)
@@ -1195,11 +1241,11 @@ def assert_frame_equal(
right.columns,
exact=check_column_type,
check_names=check_names,
- check_exact=check_exact,
+ check_exact=_check_exact,
check_categorical=check_categorical,
check_order=not check_like,
- rtol=rtol,
- atol=atol,
+ rtol=_rtol,
+ atol=_atol,
obj=f"{obj}.columns",
)
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index c4ffc197298f0..784a0347cf92b 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -462,3 +462,15 @@ def test_ea_and_numpy_no_dtype_check(val, check_exact, dtype):
left = Series([1, 2, val], dtype=dtype)
right = Series(pd.array([1, 2, val]))
tm.assert_series_equal(left, right, check_dtype=False, check_exact=check_exact)
+
+
+def test_assert_series_equal_int_tol():
+ # GH#56646
+ left = Series([81, 18, 121, 38, 74, 72, 81, 81, 146, 81, 81, 170, 74, 74])
+ right = Series([72, 9, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72])
+ tm.assert_series_equal(left, right, rtol=1.5)
+
+ tm.assert_frame_equal(left.to_frame(), right.to_frame(), rtol=1.5)
+ tm.assert_extension_array_equal(
+ left.astype("Int64").values, right.astype("Int64").values, rtol=1.5
+ )
| - [ ] closes #56646 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
cc @lithomas1 | https://api.github.com/repos/pandas-dev/pandas/pulls/56724 | 2024-01-03T23:00:57Z | 2024-01-08T21:40:05Z | 2024-01-08T21:40:05Z | 2024-01-08T21:40:08Z |
Backport PR #56672 on branch 2.2.x (BUG: dictionary type astype categorical using dictionary as categories) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 043646457f604..7df6e7d0e3166 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -740,6 +740,7 @@ Categorical
^^^^^^^^^^^
- :meth:`Categorical.isin` raising ``InvalidIndexError`` for categorical containing overlapping :class:`Interval` values (:issue:`34974`)
- Bug in :meth:`CategoricalDtype.__eq__` returning ``False`` for unordered categorical data with mixed types (:issue:`55468`)
+- Bug when casting ``pa.dictionary`` to :class:`CategoricalDtype` using a ``pa.DictionaryArray`` as categories (:issue:`56672`)
Datetimelike
^^^^^^^^^^^^
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 065a942cae768..b87c5375856dc 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -44,7 +44,9 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
CategoricalDtype,
+ CategoricalDtypeType,
ExtensionDtype,
)
from pandas.core.dtypes.generic import (
@@ -443,24 +445,32 @@ def __init__(
values = arr
if dtype.categories is None:
- if not isinstance(values, ABCIndex):
- # in particular RangeIndex xref test_index_equal_range_categories
- values = sanitize_array(values, None)
- try:
- codes, categories = factorize(values, sort=True)
- except TypeError as err:
- codes, categories = factorize(values, sort=False)
- if dtype.ordered:
- # raise, as we don't have a sortable data structure and so
- # the user should give us one by specifying categories
- raise TypeError(
- "'values' is not ordered, please "
- "explicitly specify the categories order "
- "by passing in a categories argument."
- ) from err
-
- # we're inferring from values
- dtype = CategoricalDtype(categories, dtype.ordered)
+ if isinstance(values.dtype, ArrowDtype) and issubclass(
+ values.dtype.type, CategoricalDtypeType
+ ):
+ arr = values._pa_array.combine_chunks()
+ categories = arr.dictionary.to_pandas(types_mapper=ArrowDtype)
+ codes = arr.indices.to_numpy()
+ dtype = CategoricalDtype(categories, values.dtype.pyarrow_dtype.ordered)
+ else:
+ if not isinstance(values, ABCIndex):
+ # in particular RangeIndex xref test_index_equal_range_categories
+ values = sanitize_array(values, None)
+ try:
+ codes, categories = factorize(values, sort=True)
+ except TypeError as err:
+ codes, categories = factorize(values, sort=False)
+ if dtype.ordered:
+ # raise, as we don't have a sortable data structure and so
+ # the user should give us one by specifying categories
+ raise TypeError(
+ "'values' is not ordered, please "
+ "explicitly specify the categories order "
+ "by passing in a categories argument."
+ ) from err
+
+ # we're inferring from values
+ dtype = CategoricalDtype(categories, dtype.ordered)
elif isinstance(values.dtype, CategoricalDtype):
old_codes = extract_array(values)._codes
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index e709e6fcfe456..6689fb34f2ae3 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3234,6 +3234,22 @@ def test_factorize_chunked_dictionary():
tm.assert_index_equal(res_uniques, exp_uniques)
+def test_dictionary_astype_categorical():
+ # GH#56672
+ arrs = [
+ pa.array(np.array(["a", "x", "c", "a"])).dictionary_encode(),
+ pa.array(np.array(["a", "d", "c"])).dictionary_encode(),
+ ]
+ ser = pd.Series(ArrowExtensionArray(pa.chunked_array(arrs)))
+ result = ser.astype("category")
+ categories = pd.Index(["a", "x", "c", "d"], dtype=ArrowDtype(pa.string()))
+ expected = pd.Series(
+ ["a", "x", "c", "a", "a", "d", "c"],
+ dtype=pd.CategoricalDtype(categories=categories),
+ )
+ tm.assert_series_equal(result, expected)
+
+
def test_arrow_floordiv():
# GH 55561
a = pd.Series([-7], dtype="int64[pyarrow]")
| Backport PR #56672: BUG: dictionary type astype categorical using dictionary as categories | https://api.github.com/repos/pandas-dev/pandas/pulls/56723 | 2024-01-03T22:49:08Z | 2024-01-03T23:48:10Z | 2024-01-03T23:48:10Z | 2024-01-03T23:48:11Z |
Fix for #56716: Use assert_produces_warning instead of pytest.raises to show FutureWarning | diff --git a/doc/source/whatsnew/v2.3.0.rst b/doc/source/whatsnew/v2.3.0.rst
index 1f1b0c7d7195a..b6de33002251b 100644
--- a/doc/source/whatsnew/v2.3.0.rst
+++ b/doc/source/whatsnew/v2.3.0.rst
@@ -108,6 +108,7 @@ Performance improvements
Bug fixes
~~~~~~~~~
+Fixed bug in :meth:`Series.diff` and :meth:`algorithms.diff` for no arg validation unlike :meth:`Dataframe.diff` for periods. (:issue:`56607`)
Categorical
^^^^^^^^^^^
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 76fdcefd03407..128477dac562e 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -47,6 +47,7 @@
is_complex_dtype,
is_dict_like,
is_extension_array_dtype,
+ is_float,
is_float_dtype,
is_integer,
is_integer_dtype,
@@ -1361,7 +1362,12 @@ def diff(arr, n: int, axis: AxisInt = 0):
shifted
"""
- n = int(n)
+ # added a check on the integer value of period
+ # see https://github.com/pandas-dev/pandas/issues/56607
+ if not lib.is_integer(n):
+ if not (is_float(n) and n.is_integer()):
+ raise ValueError("periods must be an integer")
+ n = int(n)
na = np.nan
dtype = arr.dtype
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 1f9ac8511476e..90073e21cfd66 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -72,6 +72,7 @@
)
from pandas.core.dtypes.common import (
is_dict_like,
+ is_float,
is_integer,
is_iterator,
is_list_like,
@@ -3102,6 +3103,9 @@ def diff(self, periods: int = 1) -> Series:
--------
{examples}
"""
+ if not lib.is_integer(periods):
+ if not (is_float(periods) and periods.is_integer()):
+ raise ValueError("periods must be an integer")
result = algorithms.diff(self._values, periods)
return self._constructor(result, index=self.index, copy=False).__finalize__(
self, method="diff"
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py
index 5451f7b2f16f5..2e1197cff8875 100644
--- a/pandas/tests/io/xml/test_xml.py
+++ b/pandas/tests/io/xml/test_xml.py
@@ -497,10 +497,9 @@ def test_wrong_file_path(parser):
)
filename = os.path.join("data", "html", "books.xml")
- with pytest.raises(
- FutureWarning,
- match=msg,
- ):
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match=msg):
read_xml(filename, parser=parser)
@@ -1369,7 +1368,8 @@ def test_empty_stylesheet(val):
)
kml = os.path.join("data", "xml", "cta_rail_lines.kml")
- with pytest.raises(FutureWarning, match=msg):
+ # 56716: Use assert_produces_warning instead of pytest.raises to show FutureWarning
+ with tm.assert_produces_warning(FutureWarning, match=msg):
read_xml(kml, stylesheet=val)
diff --git a/pandas/tests/series/methods/test_diff.py b/pandas/tests/series/methods/test_diff.py
index 18de81a927c3a..a46389087f87b 100644
--- a/pandas/tests/series/methods/test_diff.py
+++ b/pandas/tests/series/methods/test_diff.py
@@ -10,6 +10,11 @@
class TestSeriesDiff:
+ def test_diff_series_requires_integer(self):
+ series = Series(np.random.default_rng(2).standard_normal(2))
+ with pytest.raises(ValueError, match="periods must be an integer"):
+ series.diff(1.5)
+
def test_diff_np(self):
# TODO(__array_function__): could make np.diff return a Series
# matching ser.diff()
| - [1] closes #56716
- [2] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [3] Replaced FutureWarning using pytest: pytest.raises(FutureWarning, match=msg):
with tm.assert_produces_warning
| https://api.github.com/repos/pandas-dev/pandas/pulls/56722 | 2024-01-03T22:38:00Z | 2024-01-23T17:56:19Z | null | 2024-01-29T19:03:08Z |
DOC: Fixup read_csv docstring | diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index a9b41b45aba2f..e26e7e7470461 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -396,7 +396,7 @@
- Callable, function with signature
as described in `pyarrow documentation
<https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html
- #pyarrow.csv.ParseOptions.invalid_row_handler>_` when ``engine='pyarrow'``
+ #pyarrow.csv.ParseOptions.invalid_row_handler>`_ when ``engine='pyarrow'``
delim_whitespace : bool, default False
Specifies whether or not whitespace (e.g. ``' '`` or ``'\\t'``) will be
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56721 | 2024-01-03T22:35:06Z | 2024-01-03T23:31:42Z | 2024-01-03T23:31:42Z | 2024-01-04T08:21:53Z |
Backport PR #56616 on branch 2.2.x (BUG: Add limit_area to EA ffill/bfill) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 043646457f604..75ba7c9f72c1b 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -321,7 +321,7 @@ Other enhancements
- :meth:`DataFrame.apply` now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- :meth:`ExtensionArray._explode` interface method added to allow extension type implementations of the ``explode`` method (:issue:`54833`)
- :meth:`ExtensionArray.duplicated` added to allow extension type implementations of the ``duplicated`` method (:issue:`55255`)
-- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
+- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area``; 3rd party :class:`.ExtensionArray` authors need to add this argument to the method ``_pad_or_backfill`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
- Implemented :meth:`Series.dt` methods and attributes for :class:`ArrowDtype` with ``pyarrow.duration`` type (:issue:`52284`)
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 9ece12cf51a7b..0da121c36644a 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -305,7 +305,12 @@ def _fill_mask_inplace(
func(self._ndarray.T, limit=limit, mask=mask.T)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
mask = self.isna()
if mask.any():
@@ -315,7 +320,7 @@ def _pad_or_backfill(
npvalues = self._ndarray.T
if copy:
npvalues = npvalues.copy()
- func(npvalues, limit=limit, mask=mask.T)
+ func(npvalues, limit=limit, limit_area=limit_area, mask=mask.T)
npvalues = npvalues.T
if copy:
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 5427cee55dfb1..0bc01d2da330a 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -1005,13 +1005,18 @@ def dropna(self) -> Self:
return type(self)(pc.drop_null(self._pa_array))
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
if not self._hasna:
# TODO(CoW): Not necessary anymore when CoW is the default
return self.copy()
- if limit is None:
+ if limit is None and limit_area is None:
method = missing.clean_fill_method(method)
try:
if method == "pad":
@@ -1027,7 +1032,9 @@ def _pad_or_backfill(
# TODO(3.0): after EA.fillna 'method' deprecation is enforced, we can remove
# this method entirely.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
@doc(ExtensionArray.fillna)
def fillna(
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 59c6d911cfaef..ea0e2e54e3339 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -70,6 +70,7 @@
unique,
)
from pandas.core.array_algos.quantile import quantile_with_mask
+from pandas.core.missing import _fill_limit_area_1d
from pandas.core.sorting import (
nargminmax,
nargsort,
@@ -954,7 +955,12 @@ def interpolate(
)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
"""
Pad or backfill values, used by Series/DataFrame ffill and bfill.
@@ -1012,6 +1018,12 @@ def _pad_or_backfill(
DeprecationWarning,
stacklevel=find_stack_level(),
)
+ if limit_area is not None:
+ raise NotImplementedError(
+ f"{type(self).__name__} does not implement limit_area "
+ "(added in pandas 2.2). 3rd-party ExtnsionArray authors "
+ "need to add this argument to _pad_or_backfill."
+ )
return self.fillna(method=method, limit=limit)
mask = self.isna()
@@ -1021,6 +1033,8 @@ def _pad_or_backfill(
meth = missing.clean_fill_method(method)
npmask = np.asarray(mask)
+ if limit_area is not None and not npmask.all():
+ _fill_limit_area_1d(npmask, limit_area)
if meth == "pad":
indexer = libalgos.get_fill_indexer(npmask, limit=limit)
return self.take(indexer, allow_fill=True)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index a19b304529383..904c87c68e211 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -890,11 +890,18 @@ def max(self, *, axis: AxisInt | None = None, skipna: bool = True) -> IntervalOr
return obj[indexer]
def _pad_or_backfill( # pylint: disable=useless-parent-delegation
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# TODO(3.0): after EA.fillna 'method' deprecation is enforced, we can remove
# this method entirely.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
def fillna(
self, value=None, method=None, limit: int | None = None, copy: bool = True
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 03c09c5b2fd18..fc092ef6eb463 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -192,7 +192,12 @@ def __getitem__(self, item: PositionalIndexer) -> Self | Any:
return self._simple_new(self._data[item], newmask)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
mask = self._mask
@@ -204,7 +209,21 @@ def _pad_or_backfill(
if copy:
npvalues = npvalues.copy()
new_mask = new_mask.copy()
+ elif limit_area is not None:
+ mask = mask.copy()
func(npvalues, limit=limit, mask=new_mask)
+
+ if limit_area is not None and not mask.all():
+ mask = mask.T
+ neg_mask = ~mask
+ first = neg_mask.argmax()
+ last = len(neg_mask) - neg_mask[::-1].argmax() - 1
+ if limit_area == "inside":
+ new_mask[:first] |= mask[:first]
+ new_mask[last + 1 :] |= mask[last + 1 :]
+ elif limit_area == "outside":
+ new_mask[first + 1 : last] |= mask[first + 1 : last]
+
if copy:
return self._simple_new(npvalues.T, new_mask.T)
else:
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 2930b979bfe78..28f25d38b2363 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -810,12 +810,19 @@ def searchsorted(
return m8arr.searchsorted(npvalue, side=side, sorter=sorter)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# view as dt64 so we get treated as timelike in core.missing,
# similar to dtl._period_dispatch
dta = self.view("M8[ns]")
- result = dta._pad_or_backfill(method=method, limit=limit, copy=copy)
+ result = dta._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
if copy:
return cast("Self", result.view(self.dtype))
else:
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 5db77db2a9c66..98d84d899094b 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -716,11 +716,18 @@ def isna(self) -> Self: # type: ignore[override]
return type(self)(mask, fill_value=False, dtype=dtype)
def _pad_or_backfill( # pylint: disable=useless-parent-delegation
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# TODO(3.0): We can remove this method once deprecation for fillna method
# keyword is enforced.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
def fillna(
self,
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 20eff9315bc80..fa409f00e9ff6 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from functools import wraps
+import inspect
import re
from typing import (
TYPE_CHECKING,
@@ -2256,11 +2257,21 @@ def pad_or_backfill(
) -> list[Block]:
values = self.values
+ kwargs: dict[str, Any] = {"method": method, "limit": limit}
+ if "limit_area" in inspect.signature(values._pad_or_backfill).parameters:
+ kwargs["limit_area"] = limit_area
+ elif limit_area is not None:
+ raise NotImplementedError(
+ f"{type(values).__name__} does not implement limit_area "
+ "(added in pandas 2.2). 3rd-party ExtnsionArray authors "
+ "need to add this argument to _pad_or_backfill."
+ )
+
if values.ndim == 2 and axis == 1:
# NDArrayBackedExtensionArray.fillna assumes axis=0
- new_values = values.T._pad_or_backfill(method=method, limit=limit).T
+ new_values = values.T._pad_or_backfill(**kwargs).T
else:
- new_values = values._pad_or_backfill(method=method, limit=limit)
+ new_values = values._pad_or_backfill(**kwargs)
return [self.make_block_same_class(new_values)]
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index d275445983b6f..5dd9aaf5fbb4a 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -3,10 +3,7 @@
"""
from __future__ import annotations
-from functools import (
- partial,
- wraps,
-)
+from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
@@ -823,6 +820,7 @@ def _interpolate_with_limit_area(
values,
method=method,
limit=limit,
+ limit_area=limit_area,
)
if limit_area == "inside":
@@ -863,27 +861,6 @@ def pad_or_backfill_inplace(
-----
Modifies values in-place.
"""
- if limit_area is not None:
- np.apply_along_axis(
- # error: Argument 1 to "apply_along_axis" has incompatible type
- # "partial[None]"; expected
- # "Callable[..., Union[_SupportsArray[dtype[<nothing>]],
- # Sequence[_SupportsArray[dtype[<nothing>]]],
- # Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]],
- # Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]],
- # Sequence[Sequence[Sequence[Sequence[_
- # SupportsArray[dtype[<nothing>]]]]]]]]"
- partial( # type: ignore[arg-type]
- _interpolate_with_limit_area,
- method=method,
- limit=limit,
- limit_area=limit_area,
- ),
- axis,
- values,
- )
- return
-
transf = (lambda x: x) if axis == 0 else (lambda x: x.T)
# reshape a 1 dim if needed
@@ -897,8 +874,7 @@ def pad_or_backfill_inplace(
func = get_fill_func(method, ndim=2)
# _pad_2d and _backfill_2d both modify tvalues inplace
- func(tvalues, limit=limit)
- return
+ func(tvalues, limit=limit, limit_area=limit_area)
def _fillna_prep(
@@ -909,7 +885,6 @@ def _fillna_prep(
if mask is None:
mask = isna(values)
- mask = mask.view(np.uint8)
return mask
@@ -919,16 +894,23 @@ def _datetimelike_compat(func: F) -> F:
"""
@wraps(func)
- def new_func(values, limit: int | None = None, mask=None):
+ def new_func(
+ values,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ mask=None,
+ ):
if needs_i8_conversion(values.dtype):
if mask is None:
# This needs to occur before casting to int64
mask = isna(values)
- result, mask = func(values.view("i8"), limit=limit, mask=mask)
+ result, mask = func(
+ values.view("i8"), limit=limit, limit_area=limit_area, mask=mask
+ )
return result.view(values.dtype), mask
- return func(values, limit=limit, mask=mask)
+ return func(values, limit=limit, limit_area=limit_area, mask=mask)
return cast(F, new_func)
@@ -937,9 +919,12 @@ def new_func(values, limit: int | None = None, mask=None):
def _pad_1d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
+ if limit_area is not None and not mask.all():
+ _fill_limit_area_1d(mask, limit_area)
algos.pad_inplace(values, mask, limit=limit)
return values, mask
@@ -948,9 +933,12 @@ def _pad_1d(
def _backfill_1d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
+ if limit_area is not None and not mask.all():
+ _fill_limit_area_1d(mask, limit_area)
algos.backfill_inplace(values, mask, limit=limit)
return values, mask
@@ -959,9 +947,12 @@ def _backfill_1d(
def _pad_2d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
):
mask = _fillna_prep(values, mask)
+ if limit_area is not None:
+ _fill_limit_area_2d(mask, limit_area)
if values.size:
algos.pad_2d_inplace(values, mask, limit=limit)
@@ -973,9 +964,14 @@ def _pad_2d(
@_datetimelike_compat
def _backfill_2d(
- values, limit: int | None = None, mask: npt.NDArray[np.bool_] | None = None
+ values,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ mask: npt.NDArray[np.bool_] | None = None,
):
mask = _fillna_prep(values, mask)
+ if limit_area is not None:
+ _fill_limit_area_2d(mask, limit_area)
if values.size:
algos.backfill_2d_inplace(values, mask, limit=limit)
@@ -985,6 +981,63 @@ def _backfill_2d(
return values, mask
+def _fill_limit_area_1d(
+ mask: npt.NDArray[np.bool_], limit_area: Literal["outside", "inside"]
+) -> None:
+ """Prepare 1d mask for ffill/bfill with limit_area.
+
+ Caller is responsible for checking at least one value of mask is False.
+ When called, mask will no longer faithfully represent when
+ the corresponding are NA or not.
+
+ Parameters
+ ----------
+ mask : np.ndarray[bool, ndim=1]
+ Mask representing NA values when filling.
+ limit_area : { "outside", "inside" }
+ Whether to limit filling to outside or inside the outer most non-NA value.
+ """
+ neg_mask = ~mask
+ first = neg_mask.argmax()
+ last = len(neg_mask) - neg_mask[::-1].argmax() - 1
+ if limit_area == "inside":
+ mask[:first] = False
+ mask[last + 1 :] = False
+ elif limit_area == "outside":
+ mask[first + 1 : last] = False
+
+
+def _fill_limit_area_2d(
+ mask: npt.NDArray[np.bool_], limit_area: Literal["outside", "inside"]
+) -> None:
+ """Prepare 2d mask for ffill/bfill with limit_area.
+
+ When called, mask will no longer faithfully represent when
+ the corresponding are NA or not.
+
+ Parameters
+ ----------
+ mask : np.ndarray[bool, ndim=1]
+ Mask representing NA values when filling.
+ limit_area : { "outside", "inside" }
+ Whether to limit filling to outside or inside the outer most non-NA value.
+ """
+ neg_mask = ~mask.T
+ if limit_area == "outside":
+ # Identify inside
+ la_mask = (
+ np.maximum.accumulate(neg_mask, axis=0)
+ & np.maximum.accumulate(neg_mask[::-1], axis=0)[::-1]
+ )
+ else:
+ # Identify outside
+ la_mask = (
+ ~np.maximum.accumulate(neg_mask, axis=0)
+ | ~np.maximum.accumulate(neg_mask[::-1], axis=0)[::-1]
+ )
+ mask[la_mask.T] = False
+
+
_fill_methods = {"pad": _pad_1d, "backfill": _backfill_1d}
diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py
index ffb7a24b4b390..dbd6682c12123 100644
--- a/pandas/tests/extension/base/missing.py
+++ b/pandas/tests/extension/base/missing.py
@@ -77,6 +77,28 @@ def test_fillna_limit_pad(self, data_missing):
expected = pd.Series(data_missing.take([1, 1, 1, 0, 1]))
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ arr = data_missing.take(input_ilocs)
+ result = pd.Series(arr).ffill(limit_area=limit_area)
+ expected = pd.Series(data_missing.take(expected_ilocs))
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.filterwarnings(
"ignore:Series.fillna with 'method' is deprecated:FutureWarning"
)
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index b3c57ee49a724..9907e345ada63 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -156,6 +156,36 @@ def test_fillna_limit_pad(self, data_missing):
):
super().test_fillna_limit_pad(data_missing)
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ msg = "ExtensionArray.fillna 'method' keyword is deprecated"
+ with tm.assert_produces_warning(
+ DeprecationWarning,
+ match=msg,
+ check_stacklevel=False,
+ raise_on_extra_warnings=False,
+ ):
+ msg = "DecimalArray does not implement limit_area"
+ with pytest.raises(NotImplementedError, match=msg):
+ super().test_ffill_limit_area(
+ data_missing, limit_area, input_ilocs, expected_ilocs
+ )
+
def test_fillna_limit_backfill(self, data_missing):
msg = "Series.fillna with 'method' is deprecated"
with tm.assert_produces_warning(
diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py
index d3d9dcc4a4712..31f44f886add7 100644
--- a/pandas/tests/extension/json/array.py
+++ b/pandas/tests/extension/json/array.py
@@ -235,6 +235,10 @@ def _values_for_argsort(self):
frozen = [tuple(x.items()) for x in self]
return construct_1d_object_array_from_listlike(frozen)
+ def _pad_or_backfill(self, *, method, limit=None, copy=True):
+ # GH#56616 - test EA method without limit_area argument
+ return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+
def make_data():
# TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 7686bc5abb44c..a18edac9aef93 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -149,6 +149,29 @@ def test_fillna_frame(self):
"""We treat dictionaries as a mapping in fillna, not a scalar."""
super().test_fillna_frame()
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ msg = "JSONArray does not implement limit_area"
+ with pytest.raises(NotImplementedError, match=msg):
+ super().test_ffill_limit_area(
+ data_missing, limit_area, input_ilocs, expected_ilocs
+ )
+
@unhashable
def test_value_counts(self, all_data, dropna):
super().test_value_counts(all_data, dropna)
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index 6757669351c5c..89c50a8c21e1c 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -862,41 +862,29 @@ def test_pad_backfill_deprecated(func):
@pytest.mark.parametrize(
"data, expected_data, method, kwargs",
(
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan],
"ffill",
{"limit_area": "inside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan],
"ffill",
{"limit_area": "inside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0],
"ffill",
{"limit_area": "outside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan],
"ffill",
{"limit_area": "outside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
(
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
@@ -910,41 +898,29 @@ def test_pad_backfill_deprecated(func):
"ffill",
{"limit_area": "outside", "limit": 1},
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "inside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "inside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "outside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "outside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
),
)
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index 89b67ddd9f5b6..0d724779abfda 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -58,6 +58,7 @@
"_iLocIndexer",
# TODO(3.0): GH#55043 - remove upon removal of ArrayManager
"_get_option",
+ "_fill_limit_area_1d",
}
| Backport PR #56616: BUG: Add limit_area to EA ffill/bfill | https://api.github.com/repos/pandas-dev/pandas/pulls/56720 | 2024-01-03T22:14:40Z | 2024-01-03T23:31:08Z | 2024-01-03T23:31:08Z | 2024-01-03T23:31:08Z |
Backport PR #56699 on branch 2.2.x (DOC: Corrected typo in warning on coerce) | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 51b4c4f297b07..d4eb5742ef928 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -432,7 +432,7 @@ In a future version, these will raise an error and you should cast to a common d
In [3]: ser[0] = 'not an int64'
FutureWarning:
- Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas.
+ Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas.
Value 'not an int64' has dtype incompatible with int64, please explicitly cast to a compatible dtype first.
In [4]: ser
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 20eff9315bc80..b7af545bd523e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -512,7 +512,7 @@ def coerce_to_target_dtype(self, other, warn_on_upcast: bool = False) -> Block:
if warn_on_upcast:
warnings.warn(
f"Setting an item of incompatible dtype is deprecated "
- "and will raise in a future error of pandas. "
+ "and will raise an error in a future version of pandas. "
f"Value '{other}' has dtype incompatible with {self.values.dtype}, "
"please explicitly cast to a compatible dtype first.",
FutureWarning,
| Backport PR #56699: DOC: Corrected typo in warning on coerce | https://api.github.com/repos/pandas-dev/pandas/pulls/56719 | 2024-01-03T21:38:13Z | 2024-01-03T22:16:56Z | 2024-01-03T22:16:56Z | 2024-01-03T22:16:56Z |
Backport PR #56691 on branch 2.2.x (Bug pyarrow implementation of str.fullmatch matches partial string. issue #56652) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 15e98cbb2a4d7..043646457f604 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -805,6 +805,7 @@ Strings
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56404`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for :class:`ArrowDtype` with ``pyarrow.string`` dtype (:issue:`56579`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for ``string[pyarrow]`` (:issue:`54942`)
+- Bug in :meth:`str.fullmatch` when ``dtype=pandas.ArrowDtype(pyarrow.string()))`` allows partial matches when regex ends in literal //$ (:issue:`56652`)
- Bug in comparison operations for ``dtype="string[pyarrow_numpy]"`` raising if dtypes can't be compared (:issue:`56008`)
Interval
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..5427cee55dfb1 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -2277,7 +2277,7 @@ def _str_match(
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
):
- if not pat.endswith("$") or pat.endswith("//$"):
+ if not pat.endswith("$") or pat.endswith("\\$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index d5a76811a12e6..e8f614ff855c0 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -433,7 +433,7 @@ def _str_match(
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
):
- if not pat.endswith("$") or pat.endswith("//$"):
+ if not pat.endswith("$") or pat.endswith("\\$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..e709e6fcfe456 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -1903,16 +1903,21 @@ def test_str_match(pat, case, na, exp):
@pytest.mark.parametrize(
"pat, case, na, exp",
[
- ["abc", False, None, [True, None]],
- ["Abc", True, None, [False, None]],
- ["bc", True, None, [False, None]],
- ["ab", False, True, [True, True]],
- ["a[a-z]{2}", False, None, [True, None]],
- ["A[a-z]{1}", True, None, [False, None]],
+ ["abc", False, None, [True, True, False, None]],
+ ["Abc", True, None, [False, False, False, None]],
+ ["bc", True, None, [False, False, False, None]],
+ ["ab", False, None, [True, True, False, None]],
+ ["a[a-z]{2}", False, None, [True, True, False, None]],
+ ["A[a-z]{1}", True, None, [False, False, False, None]],
+ # GH Issue: #56652
+ ["abc$", False, None, [True, False, False, None]],
+ ["abc\\$", False, None, [False, True, False, None]],
+ ["Abc$", True, None, [False, False, False, None]],
+ ["Abc\\$", True, None, [False, False, False, None]],
],
)
def test_str_fullmatch(pat, case, na, exp):
- ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ ser = pd.Series(["abc", "abc$", "$abc", None], dtype=ArrowDtype(pa.string()))
result = ser.str.match(pat, case=case, na=na)
expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 3f58c6d703f8f..cd4707ac405de 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -730,6 +730,15 @@ def test_fullmatch(any_string_dtype):
tm.assert_series_equal(result, expected)
+def test_fullmatch_dollar_literal(any_string_dtype):
+ # GH 56652
+ ser = Series(["foo", "foo$foo", np.nan, "foo$"], dtype=any_string_dtype)
+ result = ser.str.fullmatch("foo\\$")
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
+ expected = Series([False, False, np.nan, True], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
def test_fullmatch_na_kwarg(any_string_dtype):
ser = Series(
["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
| xref https://github.com/pandas-dev/pandas/pull/56691 | https://api.github.com/repos/pandas-dev/pandas/pulls/56715 | 2024-01-03T18:51:14Z | 2024-01-03T21:38:27Z | 2024-01-03T21:38:27Z | 2024-01-03T21:38:32Z |
test Floordiv integral promote | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..75971f4ca109e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -776,6 +776,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` and :meth:`Series.__truediv__` for :class:`ArrowDtype` with integral dtypes raising for large divisors (:issue:`56706`)
- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..4efa5eb08a49d 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -109,7 +109,7 @@
def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
- ) -> pa.ChunkedArray:
+ ) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
@@ -120,19 +120,51 @@ def cast_for_truediv(
# Intentionally not using arrow_array.cast because it could be a scalar
# value in reflected case, and safe=False only added to
# scalar cast in pyarrow 13.
- return pc.cast(arrow_array, pa.float64(), safe=False)
- return arrow_array
+ # In arrow, common type between integral and float64 is float64,
+ # but integral type is safe casted to float64, to mirror python
+ # and numpy, we want an unsafe cast, so we cast both operands to
+ # to float64 before invoking arrow.
+ return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast(
+ pa_object, pa.float64(), safe=False
+ )
+
+ return arrow_array, pa_object
def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
right: pa.ChunkedArray | pa.Array | pa.Scalar,
) -> pa.ChunkedArray:
- # Ensure int // int -> int mirroring Python/Numpy behavior
- # as pc.floor(pc.divide_checked(int, int)) -> float
- converted_left = cast_for_truediv(left, right)
- result = pc.floor(pc.divide(converted_left, right))
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
- result = result.cast(left.type)
+ # Use divide_checked to ensure cases like -9223372036854775808 // -1
+ # don't silently overflow.
+ divided = pc.divide_checked(left, right)
+ # GH 56676: avoid storing intermediate calculating in floating point type.
+ has_remainder = pc.not_equal(pc.multiply(divided, right), left)
+ result = pc.if_else(
+ # Pass a typed arrow scalar rather than stdlib int
+ # which always inferred as int64, to prevent overflow
+ # in case of large uint64 values.
+ pc.and_(
+ pc.less(
+ pc.bit_wise_xor(left, right), pa.scalar(0, type=divided.type)
+ ),
+ has_remainder,
+ ),
+ # GH 55561: floordiv should round towards negative infinity.
+ # pc.divide_checked for integral types rounds towards 0.
+ # Avoid using subtract_checked which would incorrectly raise
+ # for -9223372036854775808 // 1, because if integer overflow
+ # occurs, then has_remainder should be false, and overflowed
+ # value is discarded.
+ pc.subtract(divided, pa.scalar(1, type=divided.type)),
+ divided,
+ )
+ else:
+ # Use divide instead of divide_checked to match numpy
+ # floordiv where divide by 0 returns infinity for floating
+ # point types.
+ divided = pc.divide(left, right)
+ result = pc.floor(divided)
return result
ARROW_ARITHMETIC_FUNCS = {
@@ -142,8 +174,8 @@ def floordiv_compat(
"rsub": lambda x, y: pc.subtract_checked(y, x),
"mul": pc.multiply_checked,
"rmul": lambda x, y: pc.multiply_checked(y, x),
- "truediv": lambda x, y: pc.divide(cast_for_truediv(x, y), y),
- "rtruediv": lambda x, y: pc.divide(y, cast_for_truediv(x, y)),
+ "truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)),
+ "rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..b0fbb3139b5d5 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -905,8 +905,9 @@ def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
else:
assert pa.types.is_decimal(alt_dtype.pyarrow_dtype)
return expected.astype(alt_dtype)
-
- else:
+ elif op_name not in ["__floordiv__", "__rfloordiv__"] or isinstance(
+ other, pd.Series
+ ):
pa_expected = pa_expected.cast(orig_pa_type)
pd_expected = type(expected_data._values)(pa_expected)
@@ -3239,13 +3240,71 @@ def test_arrow_floordiv():
def test_arrow_floordiv_large_values():
- # GH 55561
+ # GH 56645
a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
expected = pd.Series([1425801600000], dtype="int64[pyarrow]")
result = a // 1_000_000
tm.assert_series_equal(result, expected)
+def test_arrow_floordiv_large_integral_result():
+ # GH 56676
+ a = pd.Series([18014398509481983, -9223372036854775808], dtype="int64[pyarrow]")
+ result = a // 1
+ tm.assert_series_equal(result, a)
+
+
+def test_arrow_floordiv_larger_divisor():
+ # GH 56676
+ a = pd.Series([-23], dtype="int64[pyarrow]")
+ result = a // 24
+ expected = pd.Series([-1], dtype="int64[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+
+def test_arrow_floordiv_integral_invalid():
+ # GH 56676
+ a = pd.Series([-9223372036854775808], dtype="int64[pyarrow]")
+ with pytest.raises(pa.lib.ArrowInvalid, match="overflow"):
+ a // -1
+ with pytest.raises(pa.lib.ArrowInvalid, match="divide by zero"):
+ a // 0
+
+
+def test_arrow_floordiv_floating_0_divisor():
+ # GH 56676
+ a = pd.Series([2], dtype="double[pyarrow]")
+ result = a // 0
+ expected = pd.Series([float("inf")], dtype="double[pyarrow]")
+ tm.assert_series_equal(result, expected)
+
+
+def test_arrow_floordiv_no_overflow():
+ # GH 56676
+ a = pd.Series([9223372036854775808], dtype="uint64[pyarrow]")
+ b = pd.Series([1], dtype="uint64[pyarrow]")
+ result = a // b
+ tm.assert_series_equal(result, a)
+
+
+def test_arrow_true_division_large_divisor():
+ # GH 56706
+ a = pd.Series([0], dtype="int64[pyarrow]")
+ b = pd.Series([18014398509481983], dtype="int64[pyarrow]")
+ expected = pd.Series([0], dtype="float64[pyarrow]")
+ result = a / b
+ tm.assert_series_equal(result, expected)
+
+
+def test_arrow_floor_division_large_divisor():
+ # GH 56706
+ a = pd.Series([0], dtype="int64[pyarrow]")
+ b = pd.Series([18014398509481983], dtype="int64[pyarrow]")
+ expected = pd.Series([0], dtype="int64[pyarrow]")
+ result = a // b
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56711 | 2024-01-03T06:11:13Z | 2024-01-03T07:10:23Z | null | 2024-01-03T07:10:23Z |
TST/CLN: Reuse more existing fixtures | diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index a3f15467feb14..bcc52f197ee51 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -194,18 +194,17 @@ def test_add_timedeltaarraylike(self, tda):
class TestTimedeltaArray:
- @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
- def test_astype_int(self, dtype):
+ def test_astype_int(self, any_int_numpy_dtype):
arr = TimedeltaArray._from_sequence(
[Timedelta("1h"), Timedelta("2h")], dtype="m8[ns]"
)
- if np.dtype(dtype) != np.int64:
+ if np.dtype(any_int_numpy_dtype) != np.int64:
with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
- arr.astype(dtype)
+ arr.astype(any_int_numpy_dtype)
return
- result = arr.astype(dtype)
+ result = arr.astype(any_int_numpy_dtype)
expected = arr._ndarray.view("i8")
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 17630f14b08c7..ed3ea1b0bd0dc 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -606,11 +606,10 @@ def test_unary_in_array(self):
)
tm.assert_numpy_array_equal(result, expected)
- @pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize("expr", ["x < -0.1", "-5 > x"])
- def test_float_comparison_bin_op(self, dtype, expr):
+ def test_float_comparison_bin_op(self, float_numpy_dtype, expr):
# GH 16363
- df = DataFrame({"x": np.array([0], dtype=dtype)})
+ df = DataFrame({"x": np.array([0], dtype=float_numpy_dtype)})
res = df.eval(expr)
assert res.values == np.array([False])
@@ -747,15 +746,16 @@ class TestTypeCasting:
@pytest.mark.parametrize("op", ["+", "-", "*", "**", "/"])
# maybe someday... numexpr has too many upcasting rules now
# chain(*(np.core.sctypes[x] for x in ['uint', 'int', 'float']))
- @pytest.mark.parametrize("dt", [np.float32, np.float64])
@pytest.mark.parametrize("left_right", [("df", "3"), ("3", "df")])
- def test_binop_typecasting(self, engine, parser, op, dt, left_right):
- df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), dtype=dt)
+ def test_binop_typecasting(self, engine, parser, op, float_numpy_dtype, left_right):
+ df = DataFrame(
+ np.random.default_rng(2).standard_normal((5, 3)), dtype=float_numpy_dtype
+ )
left, right = left_right
s = f"{left} {op} {right}"
res = pd.eval(s, engine=engine, parser=parser)
- assert df.values.dtype == dt
- assert res.values.dtype == dt
+ assert df.values.dtype == float_numpy_dtype
+ assert res.values.dtype == float_numpy_dtype
tm.assert_frame_equal(res, eval(s))
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 1b83c048411a8..a1868919be685 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -1682,16 +1682,15 @@ def exp_single_cats_value(self):
)
return exp_single_cats_value
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_loc_iloc_setitem_list_of_lists(self, orig, indexer):
+ def test_loc_iloc_setitem_list_of_lists(self, orig, indexer_li):
# - assign multiple rows (mixed values) -> exp_multi_row
df = orig.copy()
key = slice(2, 4)
- if indexer is tm.loc:
+ if indexer_li is tm.loc:
key = slice("j", "k")
- indexer(df)[key, :] = [["b", 2], ["b", 2]]
+ indexer_li(df)[key, :] = [["b", 2], ["b", 2]]
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
@@ -1701,7 +1700,7 @@ def test_loc_iloc_setitem_list_of_lists(self, orig, indexer):
df = orig.copy()
with pytest.raises(TypeError, match=msg1):
- indexer(df)[key, :] = [["c", 2], ["c", 2]]
+ indexer_li(df)[key, :] = [["c", 2], ["c", 2]]
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat])
def test_loc_iloc_at_iat_setitem_single_value_in_categories(
@@ -1722,32 +1721,30 @@ def test_loc_iloc_at_iat_setitem_single_value_in_categories(
with pytest.raises(TypeError, match=msg1):
indexer(df)[key] = "c"
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
def test_loc_iloc_setitem_mask_single_value_in_categories(
- self, orig, exp_single_cats_value, indexer
+ self, orig, exp_single_cats_value, indexer_li
):
# mask with single True
df = orig.copy()
mask = df.index == "j"
key = 0
- if indexer is tm.loc:
+ if indexer_li is tm.loc:
key = df.columns[key]
- indexer(df)[mask, key] = "b"
+ indexer_li(df)[mask, key] = "b"
tm.assert_frame_equal(df, exp_single_cats_value)
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer):
+ def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer_li):
# - assign a complete row (mixed values) -> exp_single_row
df = orig.copy()
key = 2
- if indexer is tm.loc:
+ if indexer_li is tm.loc:
key = df.index[2]
# not categorical dtype, but "b" _is_ among the categories for df["cat"]
- indexer(df)[key, :] = ["b", 2]
+ indexer_li(df)[key, :] = ["b", 2]
cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
values1 = [1, 1, 2, 1, 1, 1, 1]
@@ -1756,23 +1753,22 @@ def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer):
# "c" is not among the categories for df["cat"]
with pytest.raises(TypeError, match=msg1):
- indexer(df)[key, :] = ["c", 2]
+ indexer_li(df)[key, :] = ["c", 2]
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
def test_loc_iloc_setitem_partial_col_categorical_rhs(
- self, orig, exp_parts_cats_col, indexer
+ self, orig, exp_parts_cats_col, indexer_li
):
# assign a part of a column with dtype == categorical ->
# exp_parts_cats_col
df = orig.copy()
key = (slice(2, 4), 0)
- if indexer is tm.loc:
+ if indexer_li is tm.loc:
key = (slice("j", "k"), df.columns[0])
# same categories as we currently have in df["cats"]
compat = Categorical(["b", "b"], categories=["a", "b"])
- indexer(df)[key] = compat
+ indexer_li(df)[key] = compat
tm.assert_frame_equal(df, exp_parts_cats_col)
# categories do not match df["cat"]'s, but "b" is among them
@@ -1780,32 +1776,31 @@ def test_loc_iloc_setitem_partial_col_categorical_rhs(
with pytest.raises(TypeError, match=msg2):
# different categories but holdable values
# -> not sure if this should fail or pass
- indexer(df)[key] = semi_compat
+ indexer_li(df)[key] = semi_compat
# categories do not match df["cat"]'s, and "c" is not among them
incompat = Categorical(list("cc"), categories=list("abc"))
with pytest.raises(TypeError, match=msg2):
# different values
- indexer(df)[key] = incompat
+ indexer_li(df)[key] = incompat
- @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
def test_loc_iloc_setitem_non_categorical_rhs(
- self, orig, exp_parts_cats_col, indexer
+ self, orig, exp_parts_cats_col, indexer_li
):
# assign a part of a column with dtype != categorical -> exp_parts_cats_col
df = orig.copy()
key = (slice(2, 4), 0)
- if indexer is tm.loc:
+ if indexer_li is tm.loc:
key = (slice("j", "k"), df.columns[0])
# "b" is among the categories for df["cat"]
- indexer(df)[key] = ["b", "b"]
+ indexer_li(df)[key] = ["b", "b"]
tm.assert_frame_equal(df, exp_parts_cats_col)
# "c" not part of the categories
with pytest.raises(TypeError, match=msg1):
- indexer(df)[key] = ["c", "c"]
+ indexer_li(df)[key] = ["c", "c"]
@pytest.mark.parametrize("indexer", [tm.getitem, tm.loc, tm.iloc])
def test_getitem_preserve_object_index_with_dates(self, indexer):
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 0e0f8cf61d3d7..3f13718cfc77a 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -1000,13 +1000,12 @@ def test_setitem_slice_position(self):
expected = DataFrame(arr)
tm.assert_frame_equal(df, expected)
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
@pytest.mark.parametrize("n", [1, 2, 3])
- def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer):
+ def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer_si):
# GH#40440
df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
- indexer(df)[1:] = box([10, 11, 12])
+ indexer_si(df)[1:] = box([10, 11, 12])
expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
tm.assert_frame_equal(df, expected)
@@ -1019,15 +1018,14 @@ def test_setitem_list_indexer_broadcasting_rhs(self, n, box):
expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
tm.assert_frame_equal(df, expected)
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
@pytest.mark.parametrize("n", [1, 2, 3])
- def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):
+ def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer_si):
# GH#40440
df = DataFrame(
[[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]
)
- indexer(df)[1:] = box([10, 11, 12])
+ indexer_si(df)[1:] = box([10, 11, 12])
expected = DataFrame(
[[1, 3, 5]] + [[10, 11, 12]] * (n + 1),
columns=["a", "b", "c"],
@@ -1105,13 +1103,12 @@ def test_setitem_loc_only_false_indexer_dtype_changed(self, box):
df.loc[indexer, ["b"]] = 9
tm.assert_frame_equal(df, expected)
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc])
- def test_setitem_boolean_mask_aligning(self, indexer):
+ def test_setitem_boolean_mask_aligning(self, indexer_sl):
# GH#39931
df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]})
expected = df.copy()
mask = df["a"] >= 3
- indexer(df)[mask] = indexer(df)[mask].sort_values("a")
+ indexer_sl(df)[mask] = indexer_sl(df)[mask].sort_values("a")
tm.assert_frame_equal(df, expected)
def test_setitem_mask_categorical(self):
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index b73c759518b0e..eab8dbd2787f7 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -134,9 +134,8 @@ def test_astype_with_view_mixed_float(self, mixed_float_frame):
tf.astype(np.int64)
tf.astype(np.float32)
- @pytest.mark.parametrize("dtype", [np.int32, np.int64])
@pytest.mark.parametrize("val", [np.nan, np.inf])
- def test_astype_cast_nan_inf_int(self, val, dtype):
+ def test_astype_cast_nan_inf_int(self, val, any_int_numpy_dtype):
# see GH#14265
#
# Check NaN and inf --> raise error when converting to int.
@@ -144,7 +143,7 @@ def test_astype_cast_nan_inf_int(self, val, dtype):
df = DataFrame([val])
with pytest.raises(ValueError, match=msg):
- df.astype(dtype)
+ df.astype(any_int_numpy_dtype)
def test_astype_str(self):
# see GH#9757
@@ -323,9 +322,9 @@ def test_astype_categoricaldtype_class_raises(self, cls):
with pytest.raises(TypeError, match=xpr):
df["A"].astype(cls)
- @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
- def test_astype_extension_dtypes(self, dtype):
+ def test_astype_extension_dtypes(self, any_int_ea_dtype):
# GH#22578
+ dtype = any_int_ea_dtype
df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
expected1 = DataFrame(
@@ -348,9 +347,9 @@ def test_astype_extension_dtypes(self, dtype):
tm.assert_frame_equal(df.astype(dtype), expected1)
tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
- @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
- def test_astype_extension_dtypes_1d(self, dtype):
+ def test_astype_extension_dtypes_1d(self, any_int_ea_dtype):
# GH#22578
+ dtype = any_int_ea_dtype
df = DataFrame({"a": [1.0, 2.0, 3.0]})
expected1 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)})
@@ -433,14 +432,13 @@ def test_astype_from_datetimelike_to_object(self, dtype, unit):
else:
assert result.iloc[0, 0] == Timedelta(1, unit=unit)
- @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])
@pytest.mark.parametrize("dtype", ["M8", "m8"])
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
- def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit):
+ def test_astype_to_datetimelike_unit(self, any_real_numpy_dtype, dtype, unit):
# tests all units from numeric origination
# GH#19223 / GH#12425
dtype = f"{dtype}[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=arr_dtype)
+ arr = np.array([[1, 2, 3]], dtype=any_real_numpy_dtype)
df = DataFrame(arr)
result = df.astype(dtype)
expected = DataFrame(arr.astype(dtype))
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index be6ed91973e80..d33a7cdcf21c3 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -304,8 +304,7 @@ def test_df_string_comparison(self):
class TestFrameFlexComparisons:
# TODO: test_bool_flex_frame needs a better name
- @pytest.mark.parametrize("op", ["eq", "ne", "gt", "lt", "ge", "le"])
- def test_bool_flex_frame(self, op):
+ def test_bool_flex_frame(self, comparison_op):
data = np.random.default_rng(2).standard_normal((5, 3))
other_data = np.random.default_rng(2).standard_normal((5, 3))
df = DataFrame(data)
@@ -315,8 +314,8 @@ def test_bool_flex_frame(self, op):
# DataFrame
assert df.eq(df).values.all()
assert not df.ne(df).values.any()
- f = getattr(df, op)
- o = getattr(operator, op)
+ f = getattr(df, comparison_op.__name__)
+ o = comparison_op
# No NAs
tm.assert_frame_equal(f(other), o(df, other))
# Unaligned
@@ -459,25 +458,23 @@ def test_flex_comparison_nat(self):
result = df.ne(pd.NaT)
assert result.iloc[0, 0].item() is True
- @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
- def test_df_flex_cmp_constant_return_types(self, opname):
+ def test_df_flex_cmp_constant_return_types(self, comparison_op):
# GH 15077, non-empty DataFrame
df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
const = 2
- result = getattr(df, opname)(const).dtypes.value_counts()
+ result = getattr(df, comparison_op.__name__)(const).dtypes.value_counts()
tm.assert_series_equal(
result, Series([2], index=[np.dtype(bool)], name="count")
)
- @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"])
- def test_df_flex_cmp_constant_return_types_empty(self, opname):
+ def test_df_flex_cmp_constant_return_types_empty(self, comparison_op):
# GH 15077 empty DataFrame
df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
const = 2
empty = df.iloc[:0]
- result = getattr(empty, opname)(const).dtypes.value_counts()
+ result = getattr(empty, comparison_op.__name__)(const).dtypes.value_counts()
tm.assert_series_equal(
result, Series([2], index=[np.dtype(bool)], name="count")
)
@@ -664,11 +661,12 @@ def test_arith_flex_series(self, simple_frame):
tm.assert_frame_equal(df.div(row), df / row)
tm.assert_frame_equal(df.div(col, axis=0), (df.T / col).T)
- @pytest.mark.parametrize("dtype", ["int64", "float64"])
- def test_arith_flex_series_broadcasting(self, dtype):
+ def test_arith_flex_series_broadcasting(self, any_real_numpy_dtype):
# broadcasting issue in GH 7325
- df = DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype=dtype)
+ df = DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype=any_real_numpy_dtype)
expected = DataFrame([[np.nan, np.inf], [1.0, 1.5], [1.0, 1.25]])
+ if any_real_numpy_dtype == "float32":
+ expected = expected.astype(any_real_numpy_dtype)
result = df.div(df[0], axis="index")
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index f7a4233b3ddc9..134a585651d72 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -706,7 +706,6 @@ def test_cython_transform_series(op, args, targop):
@pytest.mark.parametrize("op", ["cumprod", "cumsum"])
-@pytest.mark.parametrize("skipna", [False, True])
@pytest.mark.parametrize(
"input, exp",
[
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56709 | 2024-01-03T02:44:37Z | 2024-01-03T19:16:11Z | 2024-01-03T19:16:11Z | 2024-01-03T19:18:47Z |
TST/CLN: Use more shared fixtures | diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 121bfb78fe5c8..1b8ad1922b9d2 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -1116,11 +1116,10 @@ def test_ufunc_compat(self, holder, dtype):
tm.assert_equal(result, expected)
# TODO: add more dtypes
- @pytest.mark.parametrize("holder", [Index, Series])
@pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
- def test_ufunc_coercions(self, holder, dtype):
- idx = holder([1, 2, 3, 4, 5], dtype=dtype, name="x")
- box = Series if holder is Series else Index
+ def test_ufunc_coercions(self, index_or_series, dtype):
+ idx = index_or_series([1, 2, 3, 4, 5], dtype=dtype, name="x")
+ box = index_or_series
result = np.sqrt(idx)
assert result.dtype == "f8" and isinstance(result, box)
diff --git a/pandas/tests/copy_view/test_constructors.py b/pandas/tests/copy_view/test_constructors.py
index c325e49e8156e..cbd0e6899bfc9 100644
--- a/pandas/tests/copy_view/test_constructors.py
+++ b/pandas/tests/copy_view/test_constructors.py
@@ -283,14 +283,13 @@ def test_dataframe_from_dict_of_series_with_reindex(dtype):
assert np.shares_memory(arr_before, arr_after)
-@pytest.mark.parametrize("cons", [Series, Index])
@pytest.mark.parametrize(
"data, dtype", [([1, 2], None), ([1, 2], "int64"), (["a", "b"], None)]
)
def test_dataframe_from_series_or_index(
- using_copy_on_write, warn_copy_on_write, data, dtype, cons
+ using_copy_on_write, warn_copy_on_write, data, dtype, index_or_series
):
- obj = cons(data, dtype=dtype)
+ obj = index_or_series(data, dtype=dtype)
obj_orig = obj.copy()
df = DataFrame(obj, dtype=dtype)
assert np.shares_memory(get_array(obj), get_array(df, 0))
@@ -303,9 +302,10 @@ def test_dataframe_from_series_or_index(
tm.assert_equal(obj, obj_orig)
-@pytest.mark.parametrize("cons", [Series, Index])
-def test_dataframe_from_series_or_index_different_dtype(using_copy_on_write, cons):
- obj = cons([1, 2], dtype="int64")
+def test_dataframe_from_series_or_index_different_dtype(
+ using_copy_on_write, index_or_series
+):
+ obj = index_or_series([1, 2], dtype="int64")
df = DataFrame(obj, dtype="int32")
assert not np.shares_memory(get_array(obj), get_array(df, 0))
if using_copy_on_write:
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index e2ef83c243957..475473218f712 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1701,19 +1701,19 @@ def test_interval_mismatched_subtype(self):
arr = np.array([first, flt_interval], dtype=object)
assert lib.infer_dtype(arr, skipna=False) == "interval"
- @pytest.mark.parametrize("klass", [pd.array, Series])
@pytest.mark.parametrize("data", [["a", "b", "c"], ["a", "b", pd.NA]])
- def test_string_dtype(self, data, skipna, klass, nullable_string_dtype):
+ def test_string_dtype(
+ self, data, skipna, index_or_series_or_array, nullable_string_dtype
+ ):
# StringArray
- val = klass(data, dtype=nullable_string_dtype)
+ val = index_or_series_or_array(data, dtype=nullable_string_dtype)
inferred = lib.infer_dtype(val, skipna=skipna)
assert inferred == "string"
- @pytest.mark.parametrize("klass", [pd.array, Series])
@pytest.mark.parametrize("data", [[True, False, True], [True, False, pd.NA]])
- def test_boolean_dtype(self, data, skipna, klass):
+ def test_boolean_dtype(self, data, skipna, index_or_series_or_array):
# BooleanArray
- val = klass(data, dtype="boolean")
+ val = index_or_series_or_array(data, dtype="boolean")
inferred = lib.infer_dtype(val, skipna=skipna)
assert inferred == "boolean"
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index 49f29b2194cae..a46663ef606f9 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -302,8 +302,7 @@ def test_dataframe_constructor_with_dtype():
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("frame", [True, False])
-def test_astype_dispatches(frame):
+def test_astype_dispatches(frame_or_series):
# This is a dtype-specific test that ensures Series[decimal].astype
# gets all the way through to ExtensionArray.astype
# Designing a reliable smoke test that works for arbitrary data types
@@ -312,12 +311,11 @@ def test_astype_dispatches(frame):
ctx = decimal.Context()
ctx.prec = 5
- if frame:
- data = data.to_frame()
+ data = frame_or_series(data)
result = data.astype(DecimalDtype(ctx))
- if frame:
+ if frame_or_series is pd.DataFrame:
result = result["a"]
assert result.dtype.context.prec == ctx.prec
diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
index 5724f79b82578..024af66ec0844 100644
--- a/pandas/tests/frame/methods/test_set_index.py
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -577,8 +577,8 @@ def test_set_index_raise_keys(self, frame_of_index_cols, drop, append):
@pytest.mark.parametrize("append", [True, False])
@pytest.mark.parametrize("drop", [True, False])
- @pytest.mark.parametrize("box", [set], ids=["set"])
- def test_set_index_raise_on_type(self, frame_of_index_cols, box, drop, append):
+ def test_set_index_raise_on_type(self, frame_of_index_cols, drop, append):
+ box = set
df = frame_of_index_cols
msg = 'The parameter "keys" may be a column key, .*'
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py
index 89404a9bd09a3..964a80f8f3310 100644
--- a/pandas/tests/groupby/aggregate/test_numba.py
+++ b/pandas/tests/groupby/aggregate/test_numba.py
@@ -52,8 +52,7 @@ def incorrect_function(values, index):
@pytest.mark.filterwarnings("ignore")
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
-@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython, as_index):
+def test_numba_vs_cython(jit, frame_or_series, nogil, parallel, nopython, as_index):
pytest.importorskip("numba")
def func_numba(values, index):
@@ -70,7 +69,7 @@ def func_numba(values, index):
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
grouped = data.groupby(0, as_index=as_index)
- if pandas_obj == "Series":
+ if frame_or_series is Series:
grouped = grouped[1]
result = grouped.agg(func_numba, engine="numba", engine_kwargs=engine_kwargs)
@@ -82,8 +81,7 @@ def func_numba(values, index):
@pytest.mark.filterwarnings("ignore")
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
-@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-def test_cache(jit, pandas_obj, nogil, parallel, nopython):
+def test_cache(jit, frame_or_series, nogil, parallel, nopython):
# Test that the functions are cached correctly if we switch functions
pytest.importorskip("numba")
@@ -104,7 +102,7 @@ def func_2(values, index):
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
grouped = data.groupby(0)
- if pandas_obj == "Series":
+ if frame_or_series is Series:
grouped = grouped[1]
result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs)
diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py
index af11dae0aabfe..b75113d3f4e14 100644
--- a/pandas/tests/groupby/transform/test_numba.py
+++ b/pandas/tests/groupby/transform/test_numba.py
@@ -50,8 +50,7 @@ def incorrect_function(values, index):
@pytest.mark.filterwarnings("ignore")
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
-@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython, as_index):
+def test_numba_vs_cython(jit, frame_or_series, nogil, parallel, nopython, as_index):
pytest.importorskip("numba")
def func(values, index):
@@ -68,7 +67,7 @@ def func(values, index):
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
grouped = data.groupby(0, as_index=as_index)
- if pandas_obj == "Series":
+ if frame_or_series is Series:
grouped = grouped[1]
result = grouped.transform(func, engine="numba", engine_kwargs=engine_kwargs)
@@ -80,8 +79,7 @@ def func(values, index):
@pytest.mark.filterwarnings("ignore")
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
-@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-def test_cache(jit, pandas_obj, nogil, parallel, nopython):
+def test_cache(jit, frame_or_series, nogil, parallel, nopython):
# Test that the functions are cached correctly if we switch functions
pytest.importorskip("numba")
@@ -102,7 +100,7 @@ def func_2(values, index):
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
grouped = data.groupby(0)
- if pandas_obj == "Series":
+ if frame_or_series is Series:
grouped = grouped[1]
result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs)
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index e0898a636474c..f36ddff223a9a 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -106,8 +106,9 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key):
expected = DataFrame({0: Series(cat.astype(object), dtype=object), 1: range(3)})
tm.assert_frame_equal(df, expected)
- @pytest.mark.parametrize("box", [array, Series])
- def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_copy_on_write):
+ def test_iloc_setitem_ea_inplace(
+ self, frame_or_series, index_or_series_or_array, using_copy_on_write
+ ):
# GH#38952 Case with not setting a full column
# IntegerArray without NAs
arr = array([1, 2, 3, 4])
@@ -119,9 +120,9 @@ def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_copy_on_write
values = obj._mgr.arrays[0]
if frame_or_series is Series:
- obj.iloc[:2] = box(arr[2:])
+ obj.iloc[:2] = index_or_series_or_array(arr[2:])
else:
- obj.iloc[:2, 0] = box(arr[2:])
+ obj.iloc[:2, 0] = index_or_series_or_array(arr[2:])
expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8"))
tm.assert_equal(obj, expected)
diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py
index 8fbb78737474c..a6aaeba1dc3a8 100644
--- a/pandas/tests/reductions/test_stat_reductions.py
+++ b/pandas/tests/reductions/test_stat_reductions.py
@@ -16,8 +16,7 @@
class TestDatetimeLikeStatReductions:
- @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
- def test_dt64_mean(self, tz_naive_fixture, box):
+ def test_dt64_mean(self, tz_naive_fixture, index_or_series_or_array):
tz = tz_naive_fixture
dti = date_range("2001-01-01", periods=11, tz=tz)
@@ -25,20 +24,19 @@ def test_dt64_mean(self, tz_naive_fixture, box):
dti = dti.take([4, 1, 3, 10, 9, 7, 8, 5, 0, 2, 6])
dtarr = dti._data
- obj = box(dtarr)
+ obj = index_or_series_or_array(dtarr)
assert obj.mean() == pd.Timestamp("2001-01-06", tz=tz)
assert obj.mean(skipna=False) == pd.Timestamp("2001-01-06", tz=tz)
# dtarr[-2] will be the first date 2001-01-1
dtarr[-2] = pd.NaT
- obj = box(dtarr)
+ obj = index_or_series_or_array(dtarr)
assert obj.mean() == pd.Timestamp("2001-01-06 07:12:00", tz=tz)
assert obj.mean(skipna=False) is pd.NaT
- @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
@pytest.mark.parametrize("freq", ["s", "h", "D", "W", "B"])
- def test_period_mean(self, box, freq):
+ def test_period_mean(self, index_or_series_or_array, freq):
# GH#24757
dti = date_range("2001-01-01", periods=11)
# shuffle so that we are not just working with monotone-increasing
@@ -48,7 +46,7 @@ def test_period_mean(self, box, freq):
msg = r"PeriodDtype\[B\] is deprecated"
with tm.assert_produces_warning(warn, match=msg):
parr = dti._data.to_period(freq)
- obj = box(parr)
+ obj = index_or_series_or_array(parr)
with pytest.raises(TypeError, match="ambiguous"):
obj.mean()
with pytest.raises(TypeError, match="ambiguous"):
@@ -62,13 +60,12 @@ def test_period_mean(self, box, freq):
with pytest.raises(TypeError, match="ambiguous"):
obj.mean(skipna=True)
- @pytest.mark.parametrize("box", [Series, pd.Index, pd.array])
- def test_td64_mean(self, box):
+ def test_td64_mean(self, index_or_series_or_array):
m8values = np.array([0, 3, -2, -7, 1, 2, -1, 3, 5, -2, 4], "m8[D]")
tdi = pd.TimedeltaIndex(m8values).as_unit("ns")
tdarr = tdi._data
- obj = box(tdarr, copy=False)
+ obj = index_or_series_or_array(tdarr, copy=False)
result = obj.mean()
expected = np.array(tdarr).mean()
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py
index f20518c7be98a..6ba2ac0104e75 100644
--- a/pandas/tests/resample/test_base.py
+++ b/pandas/tests/resample/test_base.py
@@ -30,9 +30,8 @@
date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
],
)
-@pytest.mark.parametrize("klass", [DataFrame, Series])
-def test_asfreq(klass, index, freq):
- obj = klass(range(len(index)), index=index)
+def test_asfreq(frame_or_series, index, freq):
+ obj = frame_or_series(range(len(index)), index=index)
idx_range = date_range if isinstance(index, DatetimeIndex) else timedelta_range
result = obj.resample(freq).asfreq()
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index cf77238a553d0..3be11e0a5ad2f 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -59,12 +59,11 @@ def _simple_period_range_series(start, end, freq="D"):
class TestPeriodIndex:
@pytest.mark.parametrize("freq", ["2D", "1h", "2h"])
@pytest.mark.parametrize("kind", ["period", None, "timestamp"])
- @pytest.mark.parametrize("klass", [DataFrame, Series])
- def test_asfreq(self, klass, freq, kind):
+ def test_asfreq(self, frame_or_series, freq, kind):
# GH 12884, 15944
# make sure .asfreq() returns PeriodIndex (except kind='timestamp')
- obj = klass(range(5), index=period_range("2020-01-01", periods=5))
+ obj = frame_or_series(range(5), index=period_range("2020-01-01", periods=5))
if kind == "timestamp":
expected = obj.to_timestamp().resample(freq).asfreq()
else:
@@ -1007,12 +1006,11 @@ def test_resample_t_l_deprecated(self):
offsets.BusinessHour(2),
],
)
- @pytest.mark.parametrize("klass", [DataFrame, Series])
- def test_asfreq_invalid_period_freq(self, offset, klass):
+ def test_asfreq_invalid_period_freq(self, offset, frame_or_series):
# GH#9586
msg = f"Invalid offset: '{offset.base}' for converting time series "
- obj = klass(range(5), index=period_range("2020-01-01", periods=5))
+ obj = frame_or_series(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
obj.asfreq(freq=offset)
@@ -1027,12 +1025,11 @@ def test_asfreq_invalid_period_freq(self, offset, klass):
("2Y-MAR", "2YE-MAR"),
],
)
-@pytest.mark.parametrize("klass", [DataFrame, Series])
-def test_resample_frequency_ME_QE_YE_error_message(klass, freq, freq_depr):
+def test_resample_frequency_ME_QE_YE_error_message(frame_or_series, freq, freq_depr):
# GH#9586
msg = f"for Period, please use '{freq[1:]}' instead of '{freq_depr[1:]}'"
- obj = klass(range(5), index=period_range("2020-01-01", periods=5))
+ obj = frame_or_series(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
obj.resample(freq_depr)
@@ -1057,11 +1054,10 @@ def test_corner_cases_period(simple_period_range_series):
"2BYE-MAR",
],
)
-@pytest.mark.parametrize("klass", [DataFrame, Series])
-def test_resample_frequency_invalid_freq(klass, freq_depr):
+def test_resample_frequency_invalid_freq(frame_or_series, freq_depr):
# GH#9586
msg = f"Invalid frequency: {freq_depr[1:]}"
- obj = klass(range(5), index=period_range("2020-01-01", periods=5))
+ obj = frame_or_series(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
obj.resample(freq_depr)
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py
index 5ec95cbf24b39..d8bc7974b4139 100644
--- a/pandas/tests/reshape/concat/test_concat.py
+++ b/pandas/tests/reshape/concat/test_concat.py
@@ -545,14 +545,13 @@ def test_concat_no_unnecessary_upcast(float_numpy_dtype, frame_or_series):
assert x.values.dtype == dt
-@pytest.mark.parametrize("pdt", [Series, DataFrame])
-def test_concat_will_upcast(pdt, any_signed_int_numpy_dtype):
+def test_concat_will_upcast(frame_or_series, any_signed_int_numpy_dtype):
dt = any_signed_int_numpy_dtype
- dims = pdt().ndim
+ dims = frame_or_series().ndim
dfs = [
- pdt(np.array([1], dtype=dt, ndmin=dims)),
- pdt(np.array([np.nan], ndmin=dims)),
- pdt(np.array([5], dtype=dt, ndmin=dims)),
+ frame_or_series(np.array([1], dtype=dt, ndmin=dims)),
+ frame_or_series(np.array([np.nan], ndmin=dims)),
+ frame_or_series(np.array([5], dtype=dt, ndmin=dims)),
]
x = concat(dfs)
assert x.values.dtype == "float64"
diff --git a/pandas/tests/series/methods/test_view.py b/pandas/tests/series/methods/test_view.py
index 7e0ac372cd443..9d1478cd9f689 100644
--- a/pandas/tests/series/methods/test_view.py
+++ b/pandas/tests/series/methods/test_view.py
@@ -2,9 +2,7 @@
import pytest
from pandas import (
- Index,
Series,
- array,
date_range,
)
import pandas._testing as tm
@@ -47,11 +45,10 @@ def test_view_tz(self):
@pytest.mark.parametrize(
"second", ["m8[ns]", "M8[ns]", "M8[ns, US/Central]", "period[D]"]
)
- @pytest.mark.parametrize("box", [Series, Index, array])
- def test_view_between_datetimelike(self, first, second, box):
+ def test_view_between_datetimelike(self, first, second, index_or_series_or_array):
dti = date_range("2016-01-01", periods=3)
- orig = box(dti)
+ orig = index_or_series_or_array(dti)
obj = orig.view(first)
assert obj.dtype == first
tm.assert_numpy_array_equal(np.asarray(obj.view("i8")), dti.asi8)
diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py
index dfec99f0786eb..71994d186163e 100644
--- a/pandas/tests/test_expressions.py
+++ b/pandas/tests/test_expressions.py
@@ -6,11 +6,7 @@
from pandas import option_context
import pandas._testing as tm
-from pandas.core.api import (
- DataFrame,
- Index,
- Series,
-)
+from pandas.core.api import DataFrame
from pandas.core.computation import expressions as expr
@@ -433,16 +429,15 @@ def test_frame_series_axis(self, axis, arith, _frame, monkeypatch):
"__rfloordiv__",
],
)
- @pytest.mark.parametrize("box", [DataFrame, Series, Index])
@pytest.mark.parametrize("scalar", [-5, 5])
def test_python_semantics_with_numexpr_installed(
- self, op, box, scalar, monkeypatch
+ self, op, box_with_array, scalar, monkeypatch
):
# https://github.com/pandas-dev/pandas/issues/36047
with monkeypatch.context() as m:
m.setattr(expr, "_MIN_ELEMENTS", 0)
data = np.arange(-50, 50)
- obj = box(data)
+ obj = box_with_array(data)
method = getattr(obj, op)
result = method(scalar)
@@ -454,7 +449,7 @@ def test_python_semantics_with_numexpr_installed(
# compare result element-wise with Python
for i, elem in enumerate(data):
- if box == DataFrame:
+ if box_with_array == DataFrame:
scalar_result = result.iloc[i, 0]
else:
scalar_result = result[i]
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index cb94427ae8961..4a012f34ddc3b 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -988,14 +988,13 @@ def test_to_datetime_dtarr(self, tz):
# Doesn't work on Windows since tzpath not set correctly
@td.skip_if_windows
- @pytest.mark.parametrize("arg_class", [Series, Index])
@pytest.mark.parametrize("utc", [True, False])
@pytest.mark.parametrize("tz", [None, "US/Central"])
- def test_to_datetime_arrow(self, tz, utc, arg_class):
+ def test_to_datetime_arrow(self, tz, utc, index_or_series):
pa = pytest.importorskip("pyarrow")
dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz)
- dti = arg_class(dti)
+ dti = index_or_series(dti)
dti_arrow = dti.astype(pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz)))
@@ -1003,11 +1002,11 @@ def test_to_datetime_arrow(self, tz, utc, arg_class):
expected = to_datetime(dti, utc=utc).astype(
pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz if not utc else "UTC"))
)
- if not utc and arg_class is not Series:
+ if not utc and index_or_series is not Series:
# Doesn't hold for utc=True, since that will astype
# to_datetime also returns a new object for series
assert result is dti_arrow
- if arg_class is Series:
+ if index_or_series is Series:
tm.assert_series_equal(result, expected)
else:
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index 79132591b15b3..e244615ea4629 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -10,11 +10,6 @@ def by_blocks_fixture(request):
return request.param
-@pytest.fixture(params=["DataFrame", "Series"])
-def obj_fixture(request):
- return request.param
-
-
def _assert_frame_equal_both(a, b, **kwargs):
"""
Check that two DataFrame equal.
@@ -35,16 +30,20 @@ def _assert_frame_equal_both(a, b, **kwargs):
@pytest.mark.parametrize("check_like", [True, False])
-def test_frame_equal_row_order_mismatch(check_like, obj_fixture):
+def test_frame_equal_row_order_mismatch(check_like, frame_or_series):
df1 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"])
df2 = DataFrame({"A": [3, 2, 1], "B": [6, 5, 4]}, index=["c", "b", "a"])
if not check_like: # Do not ignore row-column orderings.
- msg = f"{obj_fixture}.index are different"
+ msg = f"{frame_or_series.__name__}.index are different"
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture)
+ tm.assert_frame_equal(
+ df1, df2, check_like=check_like, obj=frame_or_series.__name__
+ )
else:
- _assert_frame_equal_both(df1, df2, check_like=check_like, obj=obj_fixture)
+ _assert_frame_equal_both(
+ df1, df2, check_like=check_like, obj=frame_or_series.__name__
+ )
@pytest.mark.parametrize(
@@ -54,11 +53,11 @@ def test_frame_equal_row_order_mismatch(check_like, obj_fixture):
(DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}), DataFrame({"A": [1, 2, 3]})),
],
)
-def test_frame_equal_shape_mismatch(df1, df2, obj_fixture):
- msg = f"{obj_fixture} are different"
+def test_frame_equal_shape_mismatch(df1, df2, frame_or_series):
+ msg = f"{frame_or_series.__name__} are different"
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, obj=obj_fixture)
+ tm.assert_frame_equal(df1, df2, obj=frame_or_series.__name__)
@pytest.mark.parametrize(
@@ -109,14 +108,14 @@ def test_empty_dtypes(check_dtype):
@pytest.mark.parametrize("check_like", [True, False])
-def test_frame_equal_index_mismatch(check_like, obj_fixture, using_infer_string):
+def test_frame_equal_index_mismatch(check_like, frame_or_series, using_infer_string):
if using_infer_string:
dtype = "string"
else:
dtype = "object"
- msg = f"""{obj_fixture}\\.index are different
+ msg = f"""{frame_or_series.__name__}\\.index are different
-{obj_fixture}\\.index values are different \\(33\\.33333 %\\)
+{frame_or_series.__name__}\\.index values are different \\(33\\.33333 %\\)
\\[left\\]: Index\\(\\['a', 'b', 'c'\\], dtype='{dtype}'\\)
\\[right\\]: Index\\(\\['a', 'b', 'd'\\], dtype='{dtype}'\\)
At positional index 2, first diff: c != d"""
@@ -125,18 +124,20 @@ def test_frame_equal_index_mismatch(check_like, obj_fixture, using_infer_string)
df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "d"])
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture)
+ tm.assert_frame_equal(
+ df1, df2, check_like=check_like, obj=frame_or_series.__name__
+ )
@pytest.mark.parametrize("check_like", [True, False])
-def test_frame_equal_columns_mismatch(check_like, obj_fixture, using_infer_string):
+def test_frame_equal_columns_mismatch(check_like, frame_or_series, using_infer_string):
if using_infer_string:
dtype = "string"
else:
dtype = "object"
- msg = f"""{obj_fixture}\\.columns are different
+ msg = f"""{frame_or_series.__name__}\\.columns are different
-{obj_fixture}\\.columns values are different \\(50\\.0 %\\)
+{frame_or_series.__name__}\\.columns values are different \\(50\\.0 %\\)
\\[left\\]: Index\\(\\['A', 'B'\\], dtype='{dtype}'\\)
\\[right\\]: Index\\(\\['A', 'b'\\], dtype='{dtype}'\\)"""
@@ -144,11 +145,13 @@ def test_frame_equal_columns_mismatch(check_like, obj_fixture, using_infer_strin
df2 = DataFrame({"A": [1, 2, 3], "b": [4, 5, 6]}, index=["a", "b", "c"])
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture)
+ tm.assert_frame_equal(
+ df1, df2, check_like=check_like, obj=frame_or_series.__name__
+ )
-def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
- obj = obj_fixture
+def test_frame_equal_block_mismatch(by_blocks_fixture, frame_or_series):
+ obj = frame_or_series.__name__
msg = f"""{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) are different
{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) values are different \\(33\\.33333 %\\)
@@ -160,7 +163,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 7]})
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
+ tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj)
@pytest.mark.parametrize(
@@ -188,14 +191,16 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
),
],
)
-def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
+def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, frame_or_series):
# see gh-20503
#
# Test ensures that `tm.assert_frame_equals` raises the right exception
# when comparing DataFrames containing differing unicode objects.
- msg = msg.format(obj=obj_fixture)
+ msg = msg.format(obj=frame_or_series.__name__)
with pytest.raises(AssertionError, match=msg):
- tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
+ tm.assert_frame_equal(
+ df1, df2, by_blocks=by_blocks_fixture, obj=frame_or_series.__name__
+ )
def test_assert_frame_equal_extension_dtype_mismatch():
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56708 | 2024-01-03T01:34:01Z | 2024-01-03T19:12:25Z | 2024-01-03T19:12:25Z | 2024-01-03T19:18:33Z |
Fix integral truediv and floordiv for pyarrow types with large divisors | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..75971f4ca109e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -776,6 +776,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` and :meth:`Series.__truediv__` for :class:`ArrowDtype` with integral dtypes raising for large divisors (:issue:`56706`)
- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..c7de54c6ee84b 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -109,7 +109,7 @@
def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
- ) -> pa.ChunkedArray:
+ ) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
@@ -120,8 +120,15 @@ def cast_for_truediv(
# Intentionally not using arrow_array.cast because it could be a scalar
# value in reflected case, and safe=False only added to
# scalar cast in pyarrow 13.
- return pc.cast(arrow_array, pa.float64(), safe=False)
- return arrow_array
+ # In arrow, common type between integral and float64 is float64,
+ # but integral type is safe casted to float64, to mirror python
+ # and numpy, we want an unsafe cast, so we cast both operands to
+ # to float64 before invoking arrow.
+ return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast(
+ pa_object, pa.float64(), safe=False
+ )
+
+ return arrow_array, pa_object
def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
@@ -129,8 +136,8 @@ def floordiv_compat(
) -> pa.ChunkedArray:
# Ensure int // int -> int mirroring Python/Numpy behavior
# as pc.floor(pc.divide_checked(int, int)) -> float
- converted_left = cast_for_truediv(left, right)
- result = pc.floor(pc.divide(converted_left, right))
+ converted_left, converted_right = cast_for_truediv(left, right)
+ result = pc.floor(pc.divide(converted_left, converted_right))
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
result = result.cast(left.type)
return result
@@ -142,8 +149,8 @@ def floordiv_compat(
"rsub": lambda x, y: pc.subtract_checked(y, x),
"mul": pc.multiply_checked,
"rmul": lambda x, y: pc.multiply_checked(y, x),
- "truediv": lambda x, y: pc.divide(cast_for_truediv(x, y), y),
- "rtruediv": lambda x, y: pc.divide(y, cast_for_truediv(x, y)),
+ "truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)),
+ "rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..24b2ac4fa8b22 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3246,6 +3246,24 @@ def test_arrow_floordiv_large_values():
tm.assert_series_equal(result, expected)
+def test_arrow_true_division_large_divisor():
+ # GH 56706
+ a = pd.Series([0], dtype="int64[pyarrow]")
+ b = pd.Series([18014398509481983], dtype="int64[pyarrow]")
+ expected = pd.Series([0], dtype="float64[pyarrow]")
+ result = a / b
+ tm.assert_series_equal(result, expected)
+
+
+def test_arrow_floor_division_large_divisor():
+ # GH 56706
+ a = pd.Series([0], dtype="int64[pyarrow]")
+ b = pd.Series([18014398509481983], dtype="int64[pyarrow]")
+ expected = pd.Series([0], dtype="int64[pyarrow]")
+ result = a // b
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| - [ ] closes #56706(Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56707 | 2024-01-03T00:49:41Z | 2024-01-03T03:57:16Z | null | 2024-01-03T03:57:16Z |
STY: Use ruff instead of black for formatting | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 4b02ad7cf886f..6033bda99e8c8 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -18,11 +18,6 @@ ci:
# manual stage hooks
skip: [pylint, pyright, mypy]
repos:
-- repo: https://github.com/hauntsaninja/black-pre-commit-mirror
- # black compiled with mypyc
- rev: 23.11.0
- hooks:
- - id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
hooks:
@@ -35,6 +30,9 @@ repos:
files: ^pandas
exclude: ^pandas/tests
args: [--select, "ANN001,ANN2", --fix-only, --exit-non-zero-on-fix]
+ - id: ruff-format
+ # TODO: "." not needed in ruff 0.1.8
+ args: ["."]
- repo: https://github.com/jendrikseipp/vulture
rev: 'v2.10'
hooks:
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 9ad1f5b31016d..86da26bead64d 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -84,9 +84,7 @@ def time_loc_slice(self, index, index_structure):
class NumericMaskedIndexing:
monotonic_list = list(range(10**6))
- non_monotonic_list = (
- list(range(50)) + [54, 53, 52, 51] + list(range(55, 10**6 - 1))
- )
+ non_monotonic_list = list(range(50)) + [54, 53, 52, 51] + list(range(55, 10**6 - 1))
params = [
("Int64", "UInt64", "Float64"),
diff --git a/asv_bench/benchmarks/io/style.py b/asv_bench/benchmarks/io/style.py
index af9eef337e78e..24fd8a0d20aba 100644
--- a/asv_bench/benchmarks/io/style.py
+++ b/asv_bench/benchmarks/io/style.py
@@ -76,7 +76,8 @@ def _style_format(self):
# apply a formatting function
# subset is flexible but hinders vectorised solutions
self.st = self.df.style.format(
- "{:,.3f}", subset=IndexSlice["row_1":f"row_{ir}", "float_1":f"float_{ic}"]
+ "{:,.3f}",
+ subset=IndexSlice["row_1" : f"row_{ir}", "float_1" : f"float_{ic}"],
)
def _style_apply_format_hide(self):
diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst
index be8249cd3a287..7e0b9c3200d3b 100644
--- a/doc/source/development/contributing_codebase.rst
+++ b/doc/source/development/contributing_codebase.rst
@@ -38,7 +38,7 @@ Pre-commit
----------
Additionally, :ref:`Continuous Integration <contributing.ci>` will run code formatting checks
-like ``black``, ``ruff``,
+like ``ruff``,
``isort``, and ``clang-format`` and more using `pre-commit hooks <https://pre-commit.com/>`_.
Any warnings from these checks will cause the :ref:`Continuous Integration <contributing.ci>` to fail; therefore,
it is helpful to run the check yourself before submitting code. This
diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi
index 3bb957812f0ed..3725bfa3362d9 100644
--- a/pandas/_libs/hashtable.pyi
+++ b/pandas/_libs/hashtable.pyi
@@ -196,7 +196,7 @@ class HashTable:
*,
return_inverse: Literal[True],
mask: None = ...,
- ) -> tuple[np.ndarray, npt.NDArray[np.intp],]: ... # np.ndarray[subclass-specific]
+ ) -> tuple[np.ndarray, npt.NDArray[np.intp]]: ... # np.ndarray[subclass-specific]
@overload
def unique(
self,
@@ -204,7 +204,10 @@ class HashTable:
*,
return_inverse: Literal[False] = ...,
mask: npt.NDArray[np.bool_],
- ) -> tuple[np.ndarray, npt.NDArray[np.bool_],]: ... # np.ndarray[subclass-specific]
+ ) -> tuple[
+ np.ndarray,
+ npt.NDArray[np.bool_],
+ ]: ... # np.ndarray[subclass-specific]
def factorize(
self,
values: np.ndarray, # np.ndarray[subclass-specific]
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi
index b9fd970e68f5b..32ecd264262d6 100644
--- a/pandas/_libs/lib.pyi
+++ b/pandas/_libs/lib.pyi
@@ -179,7 +179,8 @@ def indices_fast(
sorted_labels: list[npt.NDArray[np.int64]],
) -> dict[Hashable, npt.NDArray[np.intp]]: ...
def generate_slices(
- labels: np.ndarray, ngroups: int # const intp_t[:]
+ labels: np.ndarray,
+ ngroups: int, # const intp_t[:]
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]: ...
def count_level_2d(
mask: np.ndarray, # ndarray[uint8_t, ndim=2, cast=True],
@@ -209,5 +210,6 @@ def get_reverse_indexer(
def is_bool_list(obj: list) -> bool: ...
def dtypes_all_equal(types: list[DtypeObj]) -> bool: ...
def is_range_indexer(
- left: np.ndarray, n: int # np.ndarray[np.int64, ndim=1]
+ left: np.ndarray,
+ n: int, # np.ndarray[np.int64, ndim=1]
) -> bool: ...
diff --git a/pandas/_testing/_hypothesis.py b/pandas/_testing/_hypothesis.py
index 084ca9c306d19..f9f653f636c4c 100644
--- a/pandas/_testing/_hypothesis.py
+++ b/pandas/_testing/_hypothesis.py
@@ -54,12 +54,8 @@
DATETIME_NO_TZ = st.datetimes()
DATETIME_JAN_1_1900_OPTIONAL_TZ = st.datetimes(
- min_value=pd.Timestamp(
- 1900, 1, 1
- ).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues]
- max_value=pd.Timestamp(
- 1900, 1, 1
- ).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues]
+ min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues]
+ max_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), # pyright: ignore[reportGeneralTypeIssues]
timezones=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()),
)
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 784e11415ade6..5b2293aeebbe7 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -1010,7 +1010,8 @@ def wrapper(*args, **kwargs):
# [..., Any] | str] | dict[Hashable,Callable[..., Any] | str |
# list[Callable[..., Any] | str]]"; expected "Hashable"
nb_looper = generate_apply_looper(
- self.func, **engine_kwargs # type: ignore[arg-type]
+ self.func, # type: ignore[arg-type]
+ **engine_kwargs,
)
result = nb_looper(self.values, self.axis)
# If we made the result 2-D, squeeze it back to 1-D
diff --git a/pandas/core/arrays/_arrow_string_mixins.py b/pandas/core/arrays/_arrow_string_mixins.py
index bfff19a123a08..06c74290bd82e 100644
--- a/pandas/core/arrays/_arrow_string_mixins.py
+++ b/pandas/core/arrays/_arrow_string_mixins.py
@@ -58,7 +58,8 @@ def _str_get(self, i: int) -> Self:
self._pa_array, start=start, stop=stop, step=step
)
null_value = pa.scalar(
- None, type=self._pa_array.type # type: ignore[attr-defined]
+ None,
+ type=self._pa_array.type, # type: ignore[attr-defined]
)
result = pc.if_else(not_out_of_bounds, selected, null_value)
return type(self)(result)
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 0da121c36644a..560845d375b56 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -347,7 +347,9 @@ def fillna(
# error: Argument 2 to "check_value_size" has incompatible type
# "ExtensionArray"; expected "ndarray"
value = missing.check_value_size(
- value, mask, len(self) # type: ignore[arg-type]
+ value,
+ mask, # type: ignore[arg-type]
+ len(self),
)
if mask.any():
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index f90a4691ec263..1d0f5c60de64f 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -2855,7 +2855,8 @@ def _dt_tz_localize(
"shift_backward": "earliest",
"shift_forward": "latest",
}.get(
- nonexistent, None # type: ignore[arg-type]
+ nonexistent, # type: ignore[arg-type]
+ None,
)
if nonexistent_pa is None:
raise NotImplementedError(f"{nonexistent=} is not supported")
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 5f3d66d17a9bc..58264f2aef6f3 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -1121,7 +1121,9 @@ def fillna(
# error: Argument 2 to "check_value_size" has incompatible type
# "ExtensionArray"; expected "ndarray"
value = missing.check_value_size(
- value, mask, len(self) # type: ignore[arg-type]
+ value,
+ mask, # type: ignore[arg-type]
+ len(self),
)
if mask.any():
@@ -1490,9 +1492,7 @@ def factorize(
uniques_ea = self._from_factorized(uniques, self)
return codes, uniques_ea
- _extension_array_shared_docs[
- "repeat"
- ] = """
+ _extension_array_shared_docs["repeat"] = """
Repeat elements of a %(klass)s.
Returns a new %(klass)s where each element of the current %(klass)s
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 4668db8d75cd7..44049f73b792b 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1236,7 +1236,9 @@ def _add_timedeltalike(self, other: Timedelta | TimedeltaArray) -> Self:
# error: Unexpected keyword argument "freq" for "_simple_new" of "NDArrayBacked"
return type(self)._simple_new(
- res_values, dtype=self.dtype, freq=new_freq # type: ignore[call-arg]
+ res_values,
+ dtype=self.dtype,
+ freq=new_freq, # type: ignore[call-arg]
)
@final
@@ -1256,7 +1258,9 @@ def _add_nat(self) -> Self:
result = result.view(self._ndarray.dtype) # preserve reso
# error: Unexpected keyword argument "freq" for "_simple_new" of "NDArrayBacked"
return type(self)._simple_new(
- result, dtype=self.dtype, freq=None # type: ignore[call-arg]
+ result,
+ dtype=self.dtype,
+ freq=None, # type: ignore[call-arg]
)
@final
@@ -2162,7 +2166,9 @@ def as_unit(self, unit: str, round_ok: bool = True) -> Self:
# error: Unexpected keyword argument "freq" for "_simple_new" of
# "NDArrayBacked" [call-arg]
return type(self)._simple_new(
- new_values, dtype=new_dtype, freq=self.freq # type: ignore[call-arg]
+ new_values,
+ dtype=new_dtype,
+ freq=self.freq, # type: ignore[call-arg]
)
# TODO: annotate other as DatetimeArray | TimedeltaArray | Timestamp | Timedelta
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index febea079527e6..96ee728d6dcb7 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -122,9 +122,7 @@
}
-_interval_shared_docs[
- "class"
-] = """
+_interval_shared_docs["class"] = """
%(summary)s
Parameters
@@ -1489,9 +1487,7 @@ def set_closed(self, closed: IntervalClosedType) -> Self:
dtype = IntervalDtype(left.dtype, closed=closed)
return self._simple_new(left, right, dtype=dtype)
- _interval_shared_docs[
- "is_non_overlapping_monotonic"
- ] = """
+ _interval_shared_docs["is_non_overlapping_monotonic"] = """
Return a boolean whether the %(klass)s is non-overlapping and monotonic.
Non-overlapping means (no Intervals share points), and monotonic means
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index be7895fdb0275..9ce19ced2b356 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -1089,7 +1089,8 @@ def value_counts(self, dropna: bool = True) -> Series:
arr = IntegerArray(value_counts, mask)
index = Index(
self.dtype.construct_array_type()(
- keys, mask_index # type: ignore[arg-type]
+ keys, # type: ignore[arg-type]
+ mask_index,
)
)
return Series(arr, index=index, name="count", copy=False)
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index b2d2e82c7a81f..fafeedc01b02b 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -454,7 +454,8 @@ def __init__(
# error: Argument "dtype" to "asarray" has incompatible type
# "Union[ExtensionDtype, dtype[Any], None]"; expected "None"
sparse_values = np.asarray(
- data.sp_values, dtype=dtype # type: ignore[arg-type]
+ data.sp_values,
+ dtype=dtype, # type: ignore[arg-type]
)
elif sparse_index is None:
data = extract_array(data, extract_numpy=True)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index e98f1157572bb..490daa656f603 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1207,9 +1207,7 @@ def factorize(
uniques = Index(uniques)
return codes, uniques
- _shared_docs[
- "searchsorted"
- ] = """
+ _shared_docs["searchsorted"] = """
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted {klass} `self` such that, if the
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index b5861fbaebe9c..f0aa7363d2644 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -695,8 +695,7 @@ def visit_Call(self, node, side=None, **kwargs):
if not isinstance(key, ast.keyword):
# error: "expr" has no attribute "id"
raise ValueError(
- "keyword error in function call "
- f"'{node.func.id}'" # type: ignore[attr-defined]
+ "keyword error in function call " f"'{node.func.id}'" # type: ignore[attr-defined]
)
if key.arg:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 9a1ec2330a326..5a0867d0251e8 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -589,7 +589,9 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
# error: Argument 3 to "__call__" of "_lru_cache_wrapper" has incompatible type
# "Type[Any]"; expected "Hashable" [arg-type]
dtype, fill_value = _maybe_promote_cached(
- dtype, fill_value, type(fill_value) # type: ignore[arg-type]
+ dtype,
+ fill_value,
+ type(fill_value), # type: ignore[arg-type]
)
except TypeError:
# if fill_value is not hashable (required for caching)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 73b5804d8c168..6851955d693bc 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1405,9 +1405,7 @@ def style(self) -> Styler:
return Styler(self)
- _shared_docs[
- "items"
- ] = r"""
+ _shared_docs["items"] = r"""
Iterate over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
@@ -2030,8 +2028,7 @@ def to_dict(
orient: Literal[
"dict", "list", "series", "split", "tight", "records", "index"
] = "dict",
- into: type[MutableMappingT]
- | MutableMappingT = dict, # type: ignore[assignment]
+ into: type[MutableMappingT] | MutableMappingT = dict, # type: ignore[assignment]
index: bool = True,
) -> MutableMappingT | list[MutableMappingT]:
"""
@@ -9137,9 +9134,7 @@ def groupby(
dropna=dropna,
)
- _shared_docs[
- "pivot"
- ] = """
+ _shared_docs["pivot"] = """
Return reshaped DataFrame organized by given index / column values.
Reshape data (produce a "pivot" table) based on column values. Uses
@@ -9283,9 +9278,7 @@ def pivot(
return pivot(self, index=index, columns=columns, values=values)
- _shared_docs[
- "pivot_table"
- ] = """
+ _shared_docs["pivot_table"] = """
Create a spreadsheet-style pivot table as a DataFrame.
The levels in the pivot table will be stored in MultiIndex objects
@@ -12529,7 +12522,7 @@ def _to_dict_of_blocks(self):
mgr = cast(BlockManager, mgr_to_mgr(mgr, "block"))
return {
k: self._constructor_from_mgr(v, axes=v.axes).__finalize__(self)
- for k, v, in mgr.to_dict().items()
+ for k, v in mgr.to_dict().items()
}
@property
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c06703660f82d..b37f22339fcfd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8006,8 +8006,6 @@ def replace(
if items:
keys, values = zip(*items)
else:
- # error: Incompatible types in assignment (expression has type
- # "list[Never]", variable has type "tuple[Any, ...]")
keys, values = ([], []) # type: ignore[assignment]
are_mappings = [is_dict_like(v) for v in values]
@@ -8825,15 +8823,11 @@ def _clip_with_scalar(self, lower, upper, inplace: bool_t = False):
if lower is not None:
cond = mask | (self >= lower)
- result = result.where(
- cond, lower, inplace=inplace
- ) # type: ignore[assignment]
+ result = result.where(cond, lower, inplace=inplace) # type: ignore[assignment]
if upper is not None:
cond = mask | (self <= upper)
result = self if inplace else result
- result = result.where(
- cond, upper, inplace=inplace
- ) # type: ignore[assignment]
+ result = result.where(cond, upper, inplace=inplace) # type: ignore[assignment]
return result
@@ -12242,7 +12236,12 @@ def _accum_func(
if axis == 1:
return self.T._accum_func(
- name, func, axis=0, skipna=skipna, *args, **kwargs # noqa: B026
+ name,
+ func,
+ axis=0,
+ skipna=skipna,
+ *args, # noqa: B026
+ **kwargs,
).T
def block_accum_func(blk_values):
@@ -12720,14 +12719,16 @@ def __imul__(self, other) -> Self:
def __itruediv__(self, other) -> Self:
# error: Unsupported left operand type for / ("Type[NDFrame]")
return self._inplace_method(
- other, type(self).__truediv__ # type: ignore[operator]
+ other,
+ type(self).__truediv__, # type: ignore[operator]
)
@final
def __ifloordiv__(self, other) -> Self:
# error: Unsupported left operand type for // ("Type[NDFrame]")
return self._inplace_method(
- other, type(self).__floordiv__ # type: ignore[operator]
+ other,
+ type(self).__floordiv__, # type: ignore[operator]
)
@final
@@ -13495,9 +13496,7 @@ def last_valid_index(self) -> Hashable | None:
Series([], dtype: bool)
"""
-_shared_docs[
- "stat_func_example"
-] = """
+_shared_docs["stat_func_example"] = """
Examples
--------
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index f2e314046fb74..9598bc0db02cc 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -848,7 +848,10 @@ def value_counts(
# "List[ndarray[Any, Any]]"; expected "List[Union[Union[ExtensionArray,
# ndarray[Any, Any]], Index, Series]]
_, idx = get_join_indexers(
- left, right, sort=False, how="left" # type: ignore[arg-type]
+ left, # type: ignore[arg-type]
+ right, # type: ignore[arg-type]
+ sort=False,
+ how="left",
)
if idx is not None:
out = np.where(idx != -1, out[idx], 0)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 089e15afd465b..c9beaee55d608 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -5187,7 +5187,10 @@ def shift(
period = cast(int, period)
if freq is not None or axis != 0:
f = lambda x: x.shift(
- period, freq, axis, fill_value # pylint: disable=cell-var-from-loop
+ period, # pylint: disable=cell-var-from-loop
+ freq,
+ axis,
+ fill_value,
)
shifted = self._python_apply_general(
f, self._selected_obj, is_transform=True
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index e2224caad9e84..e68c393f8f707 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -1008,7 +1008,8 @@ def is_in_obj(gpr) -> bool:
return False
if isinstance(gpr, Series) and isinstance(obj_gpr_column, Series):
return gpr._mgr.references_same_values( # type: ignore[union-attr]
- obj_gpr_column._mgr, 0 # type: ignore[arg-type]
+ obj_gpr_column._mgr, # type: ignore[arg-type]
+ 0,
)
return False
try:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 166d6946beacf..74c1f165ac06c 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -1107,9 +1107,7 @@ def astype(self, dtype, copy: bool = True):
result._references.add_index_reference(result)
return result
- _index_shared_docs[
- "take"
- ] = """
+ _index_shared_docs["take"] = """
Return a new %(klass)s of the values selected by the indices.
For internal compatibility with numpy arrays.
@@ -1196,9 +1194,7 @@ def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool:
allow_fill = False
return allow_fill
- _index_shared_docs[
- "repeat"
- ] = """
+ _index_shared_docs["repeat"] = """
Repeat elements of a %(klass)s.
Returns a new %(klass)s where each element of the current %(klass)s
@@ -5807,7 +5803,8 @@ def asof_locs(
# types "Union[ExtensionArray, ndarray[Any, Any]]", "str"
# TODO: will be fixed when ExtensionArray.searchsorted() is fixed
locs = self._values[mask].searchsorted(
- where._values, side="right" # type: ignore[call-overload]
+ where._values,
+ side="right", # type: ignore[call-overload]
)
locs = np.where(locs > 0, locs - 1, 0)
@@ -6069,9 +6066,7 @@ def _should_fallback_to_positional(self) -> bool:
"complex",
}
- _index_shared_docs[
- "get_indexer_non_unique"
- ] = """
+ _index_shared_docs["get_indexer_non_unique"] = """
Compute indexer and mask for new index given the current index.
The indexer should be then used as an input to ndarray.take to align the
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 4fcdb87974511..b62c19bef74be 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -555,9 +555,7 @@ def _maybe_convert_i8(self, key):
right = self._maybe_convert_i8(key.right)
constructor = Interval if scalar else IntervalIndex.from_arrays
# error: "object" not callable
- return constructor(
- left, right, closed=self.closed
- ) # type: ignore[operator]
+ return constructor(left, right, closed=self.closed) # type: ignore[operator]
if scalar:
# Timestamp/Timedelta
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 1352238eb60ec..5242706e0ce23 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2673,7 +2673,8 @@ def sortlevel(
# error: Item "Hashable" of "Union[Hashable, Sequence[Hashable]]" has
# no attribute "__iter__" (not iterable)
level = [
- self._get_level_number(lev) for lev in level # type: ignore[union-attr]
+ self._get_level_number(lev)
+ for lev in level # type: ignore[union-attr]
]
sortorder = None
@@ -4056,8 +4057,6 @@ def sparsify_labels(label_list, start: int = 0, sentinel: object = ""):
for i, (p, t) in enumerate(zip(prev, cur)):
if i == k - 1:
sparse_cur.append(t)
- # error: Argument 1 to "append" of "list" has incompatible
- # type "list[Any]"; expected "tuple[Any, ...]"
result.append(sparse_cur) # type: ignore[arg-type]
break
@@ -4065,8 +4064,6 @@ def sparsify_labels(label_list, start: int = 0, sentinel: object = ""):
sparse_cur.append(sentinel)
else:
sparse_cur.extend(cur[i:])
- # error: Argument 1 to "append" of "list" has incompatible
- # type "list[Any]"; expected "tuple[Any, ...]"
result.append(sparse_cur) # type: ignore[arg-type]
break
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 06fd9ebe47eae..8a54cb2d7a189 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1843,7 +1843,8 @@ def shift(self, periods: int, fill_value: Any = None) -> list[Block]:
# error: Argument 1 to "np_can_hold_element" has incompatible type
# "Union[dtype[Any], ExtensionDtype]"; expected "dtype[Any]"
casted = np_can_hold_element(
- self.dtype, fill_value # type: ignore[arg-type]
+ self.dtype, # type: ignore[arg-type]
+ fill_value,
)
except LossySetitemError:
nb = self.coerce_to_target_dtype(fill_value)
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index b2d463a8c6c26..4445627732a9b 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -118,7 +118,9 @@ def concatenate_managers(
# type "List[BlockManager]"; expected "List[Union[ArrayManager,
# SingleArrayManager, BlockManager, SingleBlockManager]]"
return _concatenate_array_managers(
- mgrs, axes, concat_axis # type: ignore[arg-type]
+ mgrs, # type: ignore[arg-type]
+ axes,
+ concat_axis,
)
# Assertions disabled for performance
@@ -474,9 +476,7 @@ def _concatenate_join_units(join_units: list[JoinUnit], copy: bool) -> ArrayLike
# error: No overload variant of "__getitem__" of "ExtensionArray" matches
# argument type "Tuple[int, slice]"
to_concat = [
- t
- if is_1d_only_ea_dtype(t.dtype)
- else t[0, :] # type: ignore[call-overload]
+ t if is_1d_only_ea_dtype(t.dtype) else t[0, :] # type: ignore[call-overload]
for t in to_concat
]
concat_values = concat_compat(to_concat, axis=0, ea_compat_axis=True)
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index b2a915589cba7..ea74c17917279 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -535,7 +535,8 @@ def pivot(
# error: Unsupported operand types for + ("List[Any]" and "ExtensionArray")
# error: Unsupported left operand type for + ("ExtensionArray")
indexed = data.set_index(
- cols + columns_listlike, append=append # type: ignore[operator]
+ cols + columns_listlike, # type: ignore[operator]
+ append=append,
)
else:
index_list: list[Index] | list[Series]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 487f57b7390a8..1f9ac8511476e 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2023,8 +2023,7 @@ def to_dict(self, *, into: type[dict] = ...) -> dict:
)
def to_dict(
self,
- into: type[MutableMappingT]
- | MutableMappingT = dict, # type: ignore[assignment]
+ into: type[MutableMappingT] | MutableMappingT = dict, # type: ignore[assignment]
) -> MutableMappingT:
"""
Convert Series to {label -> value} dict or dict-like object.
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index 25f7e7e9f832b..3369df5da4cba 100644
--- a/pandas/core/shared_docs.py
+++ b/pandas/core/shared_docs.py
@@ -2,9 +2,7 @@
_shared_docs: dict[str, str] = {}
-_shared_docs[
- "aggregate"
-] = """
+_shared_docs["aggregate"] = """
Aggregate using one or more operations over the specified axis.
Parameters
@@ -53,9 +51,7 @@
A passed user-defined-function will be passed a Series for evaluation.
{examples}"""
-_shared_docs[
- "compare"
-] = """
+_shared_docs["compare"] = """
Compare to another {klass} and show the differences.
Parameters
@@ -85,9 +81,7 @@
.. versionadded:: 1.5.0
"""
-_shared_docs[
- "groupby"
-] = """
+_shared_docs["groupby"] = """
Group %(klass)s using a mapper or by a Series of columns.
A groupby operation involves some combination of splitting the
@@ -195,9 +189,7 @@
iterating through groups, selecting a group, aggregation, and more.
"""
-_shared_docs[
- "melt"
-] = """
+_shared_docs["melt"] = """
Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
This function is useful to massage a DataFrame into a format where one
@@ -311,9 +303,7 @@
2 c B E 5
"""
-_shared_docs[
- "transform"
-] = """
+_shared_docs["transform"] = """
Call ``func`` on self producing a {klass} with the same axis shape as self.
Parameters
@@ -438,9 +428,7 @@
6 2 n 4
"""
-_shared_docs[
- "storage_options"
-] = """storage_options : dict, optional
+_shared_docs["storage_options"] = """storage_options : dict, optional
Extra options that make sense for a particular storage connection, e.g.
host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
are forwarded to ``urllib.request.Request`` as header options. For other
@@ -450,9 +438,7 @@
<https://pandas.pydata.org/docs/user_guide/io.html?
highlight=storage_options#reading-writing-remote-files>`_."""
-_shared_docs[
- "compression_options"
-] = """compression : str or dict, default 'infer'
+_shared_docs["compression_options"] = """compression : str or dict, default 'infer'
For on-the-fly compression of the output data. If 'infer' and '%s' is
path-like, then detect compression from the following extensions: '.gz',
'.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
@@ -471,9 +457,7 @@
.. versionadded:: 1.5.0
Added support for `.tar` files."""
-_shared_docs[
- "decompression_options"
-] = """compression : str or dict, default 'infer'
+_shared_docs["decompression_options"] = """compression : str or dict, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer' and '%s' is
path-like, then detect compression from the following extensions: '.gz',
'.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
@@ -493,9 +477,7 @@
.. versionadded:: 1.5.0
Added support for `.tar` files."""
-_shared_docs[
- "replace"
-] = """
+_shared_docs["replace"] = """
Replace values given in `to_replace` with `value`.
Values of the {klass} are replaced with other values dynamically.
@@ -817,9 +799,7 @@
4 4 e e
"""
-_shared_docs[
- "idxmin"
-] = """
+_shared_docs["idxmin"] = """
Return index of first occurrence of minimum over requested axis.
NA/null values are excluded.
@@ -884,9 +864,7 @@
dtype: object
"""
-_shared_docs[
- "idxmax"
-] = """
+_shared_docs["idxmax"] = """
Return index of first occurrence of maximum over requested axis.
NA/null values are excluded.
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 1b7d632c0fa80..7c6dca3bad7d9 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -707,9 +707,7 @@ def cat(
out = res_ser.__finalize__(self._orig, method="str_cat")
return out
- _shared_docs[
- "str_split"
- ] = r"""
+ _shared_docs["str_split"] = r"""
Split strings around given separator/delimiter.
Splits the string in the Series/Index from the %(side)s,
@@ -946,9 +944,7 @@ def rsplit(self, pat=None, *, n=-1, expand: bool = False):
result, expand=expand, returns_string=expand, dtype=dtype
)
- _shared_docs[
- "str_partition"
- ] = """
+ _shared_docs["str_partition"] = """
Split the string at the %(side)s occurrence of `sep`.
This method splits the string at the %(side)s occurrence of `sep`,
@@ -1686,9 +1682,7 @@ def pad(
result = self._data.array._str_pad(width, side=side, fillchar=fillchar)
return self._wrap_result(result)
- _shared_docs[
- "str_pad"
- ] = """
+ _shared_docs["str_pad"] = """
Pad %(side)s side of strings in the Series/Index.
Equivalent to :meth:`str.%(method)s`.
@@ -2036,9 +2030,7 @@ def encode(self, encoding, errors: str = "strict"):
result = self._data.array._str_encode(encoding, errors)
return self._wrap_result(result, returns_string=False)
- _shared_docs[
- "str_strip"
- ] = r"""
+ _shared_docs["str_strip"] = r"""
Remove %(position)s characters.
Strip whitespaces (including newlines) or a set of specified characters
@@ -2143,9 +2135,7 @@ def rstrip(self, to_strip=None):
result = self._data.array._str_rstrip(to_strip)
return self._wrap_result(result)
- _shared_docs[
- "str_removefix"
- ] = r"""
+ _shared_docs["str_removefix"] = r"""
Remove a %(side)s from an object series.
If the %(side)s is not present, the original string will be returned.
@@ -2852,9 +2842,7 @@ def extractall(self, pat, flags: int = 0) -> DataFrame:
# TODO: dispatch
return str_extractall(self._orig, pat, flags)
- _shared_docs[
- "find"
- ] = """
+ _shared_docs["find"] = """
Return %(side)s indexes in each strings in the Series/Index.
Each of returned indexes corresponds to the position where the
@@ -2960,9 +2948,7 @@ def normalize(self, form):
result = self._data.array._str_normalize(form)
return self._wrap_result(result)
- _shared_docs[
- "index"
- ] = """
+ _shared_docs["index"] = """
Return %(side)s indexes in each string in Series/Index.
Each of the returned indexes corresponds to the position where the
@@ -3094,9 +3080,7 @@ def len(self):
result = self._data.array._str_len()
return self._wrap_result(result, returns_string=False)
- _shared_docs[
- "casemethods"
- ] = """
+ _shared_docs["casemethods"] = """
Convert strings in the Series/Index to %(type)s.
%(version)s
Equivalent to :meth:`str.%(method)s`.
@@ -3224,9 +3208,7 @@ def casefold(self):
result = self._data.array._str_casefold()
return self._wrap_result(result)
- _shared_docs[
- "ismethods"
- ] = """
+ _shared_docs["ismethods"] = """
Check whether all characters in each string are %(type)s.
This is equivalent to running the Python string method
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 57bc6c1379d77..576bf7215f363 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -792,7 +792,9 @@ def get_handle(
# "Union[str, BaseBuffer]"; expected "Union[Union[str, PathLike[str]],
# ReadBuffer[bytes], WriteBuffer[bytes]]"
handle = _BytesZipFile(
- handle, ioargs.mode, **compression_args # type: ignore[arg-type]
+ handle, # type: ignore[arg-type]
+ ioargs.mode,
+ **compression_args,
)
if handle.buffer.mode == "r":
handles.append(handle)
@@ -817,7 +819,8 @@ def get_handle(
# type "BaseBuffer"; expected "Union[ReadBuffer[bytes],
# WriteBuffer[bytes], None]"
handle = _BytesTarFile(
- fileobj=handle, **compression_args # type: ignore[arg-type]
+ fileobj=handle, # type: ignore[arg-type]
+ **compression_args,
)
assert isinstance(handle, _BytesTarFile)
if "r" in handle.buffer.mode:
@@ -841,7 +844,9 @@ def get_handle(
# BaseBuffer]"; expected "Optional[Union[Union[str, bytes, PathLike[str],
# PathLike[bytes]], IO[bytes]], None]"
handle = get_lzma_file()(
- handle, ioargs.mode, **compression_args # type: ignore[arg-type]
+ handle, # type: ignore[arg-type]
+ ioargs.mode,
+ **compression_args,
)
# Zstd Compression
@@ -1137,7 +1142,9 @@ def _maybe_memory_map(
# expected "BaseBuffer"
wrapped = _IOWrapper(
mmap.mmap(
- handle.fileno(), 0, access=mmap.ACCESS_READ # type: ignore[arg-type]
+ handle.fileno(),
+ 0,
+ access=mmap.ACCESS_READ, # type: ignore[arg-type]
)
)
finally:
diff --git a/pandas/io/excel/_calamine.py b/pandas/io/excel/_calamine.py
index 4f65acf1aa40e..1f721c65982d4 100644
--- a/pandas/io/excel/_calamine.py
+++ b/pandas/io/excel/_calamine.py
@@ -75,7 +75,8 @@ def load_workbook(
from python_calamine import load_workbook
return load_workbook(
- filepath_or_buffer, **engine_kwargs # type: ignore[arg-type]
+ filepath_or_buffer, # type: ignore[arg-type]
+ **engine_kwargs,
)
@property
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index c30238e412450..36c9b66f2bd47 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2170,9 +2170,7 @@ def convert(
# "Union[Type[Index], Type[DatetimeIndex]]")
factory = lambda x, **kwds: PeriodIndex.from_ordinals( # type: ignore[assignment]
x, freq=kwds.get("freq", None)
- )._rename(
- kwds["name"]
- )
+ )._rename(kwds["name"])
# making an Index instance could throw a number of different errors
try:
@@ -3181,7 +3179,9 @@ def write_array(
# error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no
# attribute "asi8"
self._handle.create_array(
- self.group, key, value.asi8 # type: ignore[union-attr]
+ self.group,
+ key,
+ value.asi8, # type: ignore[union-attr]
)
node = getattr(self.group, key)
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 2979903edf360..136056e3ff428 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -616,8 +616,7 @@ def result(self):
# error: Argument 1 to "len" has incompatible type "Union[bool,
# Tuple[Any, ...], List[Any], ndarray[Any, Any]]"; expected "Sized"
all_sec = (
- is_list_like(self.secondary_y)
- and len(self.secondary_y) == self.nseries # type: ignore[arg-type]
+ is_list_like(self.secondary_y) and len(self.secondary_y) == self.nseries # type: ignore[arg-type]
)
if sec_true or all_sec:
# if all data is plotted on secondary, return right axes
diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py
index 898abc9b78e3f..ab2dc20ccbd02 100644
--- a/pandas/plotting/_matplotlib/hist.py
+++ b/pandas/plotting/_matplotlib/hist.py
@@ -202,17 +202,13 @@ def _post_plot_logic(self, ax: Axes, data) -> None:
# error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
# type "Hashable"; expected "str"
ax.set_xlabel(
- "Frequency"
- if self.xlabel is None
- else self.xlabel # type: ignore[arg-type]
+ "Frequency" if self.xlabel is None else self.xlabel # type: ignore[arg-type]
)
ax.set_ylabel(self.ylabel) # type: ignore[arg-type]
else:
ax.set_xlabel(self.xlabel) # type: ignore[arg-type]
ax.set_ylabel(
- "Frequency"
- if self.ylabel is None
- else self.ylabel # type: ignore[arg-type]
+ "Frequency" if self.ylabel is None else self.ylabel # type: ignore[arg-type]
)
@property
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py
index bf1c0f6346f02..067bcf0b01ccb 100644
--- a/pandas/plotting/_matplotlib/timeseries.py
+++ b/pandas/plotting/_matplotlib/timeseries.py
@@ -250,9 +250,7 @@ def use_dynamic_x(ax: Axes, data: DataFrame | Series) -> bool:
if isinstance(data.index, ABCDatetimeIndex):
# error: "BaseOffset" has no attribute "_period_dtype_code"
freq_str = OFFSET_TO_PERIOD_FREQSTR.get(freq_str, freq_str)
- base = to_offset(
- freq_str, is_period=True
- )._period_dtype_code # type: ignore[attr-defined]
+ base = to_offset(freq_str, is_period=True)._period_dtype_code # type: ignore[attr-defined]
x = data.index
if base <= FreqGroup.FR_DAY.value:
return x[:1].is_normalized
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 475473218f712..5eeab778c184c 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -656,9 +656,7 @@ def test_convert_numeric_uint64_nan_values(
arr = np.array([2**63, 2**63 + 1], dtype=object)
na_values = {2**63}
- expected = (
- np.array([np.nan, 2**63 + 1], dtype=float) if coerce else arr.copy()
- )
+ expected = np.array([np.nan, 2**63 + 1], dtype=float) if coerce else arr.copy()
result = lib.maybe_convert_numeric(
arr,
na_values,
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index e1f8d8eca2537..7105755df6f88 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -843,7 +843,8 @@ def test_empty_like(self):
class TestLibMissing:
@pytest.mark.parametrize("func", [libmissing.checknull, isna])
@pytest.mark.parametrize(
- "value", na_vals + sometimes_na_vals # type: ignore[operator]
+ "value",
+ na_vals + sometimes_na_vals, # type: ignore[operator]
)
def test_checknull_na_vals(self, func, value):
assert func(value)
@@ -864,7 +865,8 @@ def test_checknull_never_na_vals(self, func, value):
assert not func(value)
@pytest.mark.parametrize(
- "value", na_vals + sometimes_na_vals # type: ignore[operator]
+ "value",
+ na_vals + sometimes_na_vals, # type: ignore[operator]
)
def test_checknull_old_na_vals(self, value):
assert libmissing.checknull(value, inf_as_na=True)
diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py
index 212e56442ee07..2170cf254fbe6 100644
--- a/pandas/tests/frame/methods/test_first_and_last.py
+++ b/pandas/tests/frame/methods/test_first_and_last.py
@@ -61,17 +61,13 @@ def test_first_last_raises(self, frame_or_series):
msg = "'first' only supports a DatetimeIndex index"
with tm.assert_produces_warning(
FutureWarning, match=deprecated_msg
- ), pytest.raises(
- TypeError, match=msg
- ): # index is not a DatetimeIndex
+ ), pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
obj.first("1D")
msg = "'last' only supports a DatetimeIndex index"
with tm.assert_produces_warning(
FutureWarning, match=last_deprecated_msg
- ), pytest.raises(
- TypeError, match=msg
- ): # index is not a DatetimeIndex
+ ), pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
obj.last("1D")
def test_last_subset(self, frame_or_series):
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index 1d0931f5982b7..79aabbcc83bbf 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -319,9 +319,7 @@ def test_rank_pct_true(self, rank_method, exp):
@pytest.mark.single_cpu
def test_pct_max_many_rows(self):
# GH 18271
- df = DataFrame(
- {"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)}
- )
+ df = DataFrame({"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)})
result = df.rank(pct=True).max()
assert (result == 1).all()
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index fbf36dbc4fb02..9d07b8ab2288f 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -232,9 +232,7 @@ def test_reset_index_level_missing(self, idx_lev):
def test_reset_index_right_dtype(self):
time = np.arange(0.0, 10, np.sqrt(2) / 2)
- s1 = Series(
- (9.81 * time**2) / 2, index=Index(time, name="time"), name="speed"
- )
+ s1 = Series((9.81 * time**2) / 2, index=Index(time, name="time"), name="speed")
df = DataFrame(s1)
reset = s1.reset_index()
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 6223a153df358..5a69c26f2ab16 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -1188,9 +1188,7 @@ def test_agg_with_one_lambda(self):
# check pd.NameAgg case
result1 = df.groupby(by="kind").agg(
- height_sqr_min=pd.NamedAgg(
- column="height", aggfunc=lambda x: np.min(x**2)
- ),
+ height_sqr_min=pd.NamedAgg(column="height", aggfunc=lambda x: np.min(x**2)),
height_max=pd.NamedAgg(column="height", aggfunc="max"),
weight_max=pd.NamedAgg(column="weight", aggfunc="max"),
)
@@ -1245,9 +1243,7 @@ def test_agg_multiple_lambda(self):
# check pd.NamedAgg case
result2 = df.groupby(by="kind").agg(
- height_sqr_min=pd.NamedAgg(
- column="height", aggfunc=lambda x: np.min(x**2)
- ),
+ height_sqr_min=pd.NamedAgg(column="height", aggfunc=lambda x: np.min(x**2)),
height_max=pd.NamedAgg(column="height", aggfunc="max"),
weight_max=pd.NamedAgg(column="weight", aggfunc="max"),
height_max_2=pd.NamedAgg(column="height", aggfunc=lambda x: np.max(x)),
diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py
index e93fc0e2a4e2e..f766894a993a0 100644
--- a/pandas/tests/indexes/datetimes/test_scalar_compat.py
+++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py
@@ -135,7 +135,8 @@ def test_dti_hour_tzaware(self, prefix):
# GH#12806
# error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] + tm.get_locales() # type: ignore[operator]
+ "time_locale",
+ [None] + tm.get_locales(), # type: ignore[operator]
)
def test_day_name_month_name(self, time_locale):
# Test Monday -> Sunday and January -> December, in that sequence
diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py
index b4dcef71dcf50..4a1a6b9c452d5 100644
--- a/pandas/tests/indexes/multi/test_sorting.py
+++ b/pandas/tests/indexes/multi/test_sorting.py
@@ -151,7 +151,7 @@ def test_unsortedindex_doc_examples():
msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(1\)"
with pytest.raises(UnsortedIndexError, match=msg):
- dfm.loc[(0, "y"):(1, "z")]
+ dfm.loc[(0, "y") : (1, "z")]
assert not dfm.index._is_lexsorted()
assert dfm.index._lexsort_depth == 1
@@ -159,7 +159,7 @@ def test_unsortedindex_doc_examples():
# sort it
dfm = dfm.sort_index()
dfm.loc[(1, "z")]
- dfm.loc[(0, "y"):(1, "z")]
+ dfm.loc[(0, "y") : (1, "z")]
assert dfm.index._is_lexsorted()
assert dfm.index._lexsort_depth == 2
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index f2458a6c6114d..29f8a0a5a5932 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -403,8 +403,9 @@ def test_get_indexer_arrow_dictionary_target(self):
tm.assert_numpy_array_equal(result, expected)
result_1, result_2 = idx.get_indexer_non_unique(target)
- expected_1, expected_2 = np.array([0, -1], dtype=np.int64), np.array(
- [1], dtype=np.int64
+ expected_1, expected_2 = (
+ np.array([0, -1], dtype=np.int64),
+ np.array([1], dtype=np.int64),
)
tm.assert_numpy_array_equal(result_1, expected_1)
tm.assert_numpy_array_equal(result_2, expected_2)
diff --git a/pandas/tests/indexes/numeric/test_join.py b/pandas/tests/indexes/numeric/test_join.py
index 918d505216735..9839f40861d55 100644
--- a/pandas/tests/indexes/numeric/test_join.py
+++ b/pandas/tests/indexes/numeric/test_join.py
@@ -313,15 +313,11 @@ def test_join_right(self, index_large):
tm.assert_numpy_array_equal(ridx, eridx)
def test_join_non_int_index(self, index_large):
- other = Index(
- 2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object
- )
+ other = Index(2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object)
outer = index_large.join(other, how="outer")
outer2 = other.join(index_large, how="outer")
- expected = Index(
- 2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")
- )
+ expected = Index(2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64"))
tm.assert_index_equal(outer, outer2)
tm.assert_index_equal(outer, expected)
@@ -353,9 +349,7 @@ def test_join_outer(self, index_large):
noidx_res = index_large.join(other, how="outer")
tm.assert_index_equal(res, noidx_res)
- eres = Index(
- 2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")
- )
+ eres = Index(2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64"))
elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp)
diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py
index 5aff1f1309004..830c187a205a8 100644
--- a/pandas/tests/indexing/multiindex/test_partial.py
+++ b/pandas/tests/indexing/multiindex/test_partial.py
@@ -93,7 +93,7 @@ def test_fancy_slice_partial(
tm.assert_frame_equal(result, expected)
ymd = multiindex_year_month_day_dataframe_random_data
- result = ymd.loc[(2000, 2):(2000, 4)]
+ result = ymd.loc[(2000, 2) : (2000, 4)]
lev = ymd.index.codes[1]
expected = ymd[(lev >= 1) & (lev <= 3)]
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py
index cef3dca054758..7f298e9bdd375 100644
--- a/pandas/tests/indexing/multiindex/test_slice.py
+++ b/pandas/tests/indexing/multiindex/test_slice.py
@@ -700,21 +700,23 @@ def test_multiindex_label_slicing_with_negative_step(self):
tm.assert_indexing_slices_equivalent(ser, SLC[::-1], SLC[::-1])
tm.assert_indexing_slices_equivalent(ser, SLC["d"::-1], SLC[15::-1])
- tm.assert_indexing_slices_equivalent(ser, SLC[("d",)::-1], SLC[15::-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[("d",) :: -1], SLC[15::-1])
tm.assert_indexing_slices_equivalent(ser, SLC[:"d":-1], SLC[:11:-1])
- tm.assert_indexing_slices_equivalent(ser, SLC[:("d",):-1], SLC[:11:-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[: ("d",) : -1], SLC[:11:-1])
tm.assert_indexing_slices_equivalent(ser, SLC["d":"b":-1], SLC[15:3:-1])
- tm.assert_indexing_slices_equivalent(ser, SLC[("d",):"b":-1], SLC[15:3:-1])
- tm.assert_indexing_slices_equivalent(ser, SLC["d":("b",):-1], SLC[15:3:-1])
- tm.assert_indexing_slices_equivalent(ser, SLC[("d",):("b",):-1], SLC[15:3:-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[("d",) : "b" : -1], SLC[15:3:-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC["d" : ("b",) : -1], SLC[15:3:-1])
+ tm.assert_indexing_slices_equivalent(
+ ser, SLC[("d",) : ("b",) : -1], SLC[15:3:-1]
+ )
tm.assert_indexing_slices_equivalent(ser, SLC["b":"d":-1], SLC[:0])
- tm.assert_indexing_slices_equivalent(ser, SLC[("c", 2)::-1], SLC[10::-1])
- tm.assert_indexing_slices_equivalent(ser, SLC[:("c", 2):-1], SLC[:9:-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[("c", 2) :: -1], SLC[10::-1])
+ tm.assert_indexing_slices_equivalent(ser, SLC[: ("c", 2) : -1], SLC[:9:-1])
tm.assert_indexing_slices_equivalent(
- ser, SLC[("e", 0):("c", 2):-1], SLC[16:9:-1]
+ ser, SLC[("e", 0) : ("c", 2) : -1], SLC[16:9:-1]
)
def test_multiindex_slice_first_level(self):
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index c455b0bc8599b..c897afaeeee0e 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1818,7 +1818,7 @@ def test_loc_setitem_multiindex_slice(self):
)
result = Series([1, 1, 1, 1, 1, 1, 1, 1], index=index)
- result.loc[("baz", "one"):("foo", "two")] = 100
+ result.loc[("baz", "one") : ("foo", "two")] = 100
expected = Series([1, 1, 100, 100, 100, 100, 1, 1], index=index)
@@ -2842,7 +2842,7 @@ def test_loc_axis_1_slice():
index=tuple("ABCDEFGHIJ"),
columns=MultiIndex.from_tuples(cols),
)
- result = df.loc(axis=1)[(2014, 9):(2015, 8)]
+ result = df.loc(axis=1)[(2014, 9) : (2015, 8)]
expected = DataFrame(
np.ones((10, 4)),
index=tuple("ABCDEFGHIJ"),
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index 1e345eb82ed3c..8cb06e3b7619d 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -93,11 +93,7 @@ def test_w3_html_format(styler):
lambda x: "att1:v1;"
).set_table_attributes('class="my-cls1" style="attr3:v3;"').set_td_classes(
DataFrame(["my-cls2"], index=["a"], columns=["A"])
- ).format(
- "{:.1f}"
- ).set_caption(
- "A comprehensive test"
- )
+ ).format("{:.1f}").set_caption("A comprehensive test")
expected = dedent(
"""\
<style type="text/css">
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 1fd96dff27d06..98f1e0245b353 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -1338,9 +1338,7 @@ def test_to_latex_multiindex_names(self, name0, name1, axes):
& 4 & -1 & -1 & -1 & -1 \\
\bottomrule
\end{tabular}
-""" % tuple(
- list(col_names) + [idx_names_row]
- )
+""" % tuple(list(col_names) + [idx_names_row])
assert observed == expected
@pytest.mark.parametrize("one_row", [True, False])
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index 56ea9ea625dff..c7d2a5845b50e 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -178,7 +178,8 @@ def test_encode_dict_with_unicode_keys(self, unicode_key):
assert unicode_dict == ujson.ujson_loads(ujson.ujson_dumps(unicode_dict))
@pytest.mark.parametrize(
- "double_input", [math.pi, -math.pi] # Should work with negatives too.
+ "double_input",
+ [math.pi, -math.pi], # Should work with negatives too.
)
def test_encode_double_conversion(self, double_input):
output = ujson.ujson_dumps(double_input)
@@ -520,7 +521,8 @@ def test_decode_invalid_dict(self, invalid_dict):
ujson.ujson_loads(invalid_dict)
@pytest.mark.parametrize(
- "numeric_int_as_str", ["31337", "-31337"] # Should work with negatives.
+ "numeric_int_as_str",
+ ["31337", "-31337"], # Should work with negatives.
)
def test_decode_numeric_int(self, numeric_int_as_str):
assert int(numeric_int_as_str) == ujson.ujson_loads(numeric_int_as_str)
diff --git a/pandas/tests/io/parser/test_converters.py b/pandas/tests/io/parser/test_converters.py
index 7f3e45324dbd2..b6b882b4ec432 100644
--- a/pandas/tests/io/parser/test_converters.py
+++ b/pandas/tests/io/parser/test_converters.py
@@ -32,7 +32,8 @@ def test_converters_type_must_be_dict(all_parsers):
@pytest.mark.parametrize("column", [3, "D"])
@pytest.mark.parametrize(
- "converter", [parse, lambda x: int(x.split("/")[2])] # Produce integer.
+ "converter",
+ [parse, lambda x: int(x.split("/")[2])], # Produce integer.
)
def test_converters(all_parsers, column, converter):
parser = all_parsers
@@ -84,9 +85,9 @@ def test_converters_euro_decimal_format(all_parsers):
1;1521,1541;187101,9543;ABC;poi;4,7387
2;121,12;14897,76;DEF;uyt;0,3773
3;878,158;108013,434;GHI;rez;2,7356"""
- converters["Number1"] = converters["Number2"] = converters[
- "Number3"
- ] = lambda x: float(x.replace(",", "."))
+ converters["Number1"] = converters["Number2"] = converters["Number3"] = (
+ lambda x: float(x.replace(",", "."))
+ )
if parser.engine == "pyarrow":
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py
index cbd3917ba9c04..155e52d76e895 100644
--- a/pandas/tests/io/parser/test_encoding.py
+++ b/pandas/tests/io/parser/test_encoding.py
@@ -57,9 +57,7 @@ def test_utf16_bom_skiprows(all_parsers, sep, encoding):
skip this too
A,B,C
1,2,3
-4,5,6""".replace(
- ",", sep
- )
+4,5,6""".replace(",", sep)
path = f"__{uuid.uuid4()}__.csv"
kwargs = {"sep": sep, "skiprows": 2}
utf8 = "utf-8"
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index bed2b5e10a6f7..b62fcc04c375c 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -488,9 +488,7 @@ def test_full_file_with_spaces():
868 Jennifer Love Hewitt 0 17000.00 5/25/1985
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
317 Bill Murray 789.65 5000.00 2/5/2007
-""".strip(
- "\r\n"
- )
+""".strip("\r\n")
colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))
expected = read_fwf(StringIO(test), colspecs=colspecs)
@@ -507,9 +505,7 @@ def test_full_file_with_spaces_and_missing():
868 5/25/1985
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
317 Bill Murray 789.65
-""".strip(
- "\r\n"
- )
+""".strip("\r\n")
colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))
expected = read_fwf(StringIO(test), colspecs=colspecs)
@@ -526,9 +522,7 @@ def test_messed_up_data():
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
317 Bill Murray 789.65
-""".strip(
- "\r\n"
- )
+""".strip("\r\n")
colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79))
expected = read_fwf(StringIO(test), colspecs=colspecs)
@@ -544,9 +538,7 @@ def test_multiple_delimiters():
++44~~~~12.01 baz~~Jennifer Love Hewitt
~~55 11+++foo++++Jada Pinkett-Smith
..66++++++.03~~~bar Bill Murray
-""".strip(
- "\r\n"
- )
+""".strip("\r\n")
delimiter = " +~.\\"
colspecs = ((0, 4), (7, 13), (15, 19), (21, 41))
expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter)
@@ -560,9 +552,7 @@ def test_variable_width_unicode():
שלום שלום
ום שלל
של ום
-""".strip(
- "\r\n"
- )
+""".strip("\r\n")
encoding = "utf8"
kwargs = {"header": None, "encoding": encoding}
diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py
index 2d50916228f14..0ca47ded7ba8a 100644
--- a/pandas/tests/io/parser/test_skiprows.py
+++ b/pandas/tests/io/parser/test_skiprows.py
@@ -189,7 +189,8 @@ def test_skip_row_with_newline_and_quote(all_parsers, data, exp_data):
@xfail_pyarrow # ValueError: The 'delim_whitespace' option is not supported
@pytest.mark.parametrize(
- "lineterminator", ["\n", "\r\n", "\r"] # "LF" # "CRLF" # "CR"
+ "lineterminator",
+ ["\n", "\r\n", "\r"], # "LF" # "CRLF" # "CR"
)
def test_skiprows_lineterminator(all_parsers, lineterminator, request):
# see gh-9079
diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py
index fef5414e85e52..1b3d1d41bc1c9 100644
--- a/pandas/tests/io/parser/test_textreader.py
+++ b/pandas/tests/io/parser/test_textreader.py
@@ -136,7 +136,10 @@ def test_skip_bad_lines(self):
reader.read()
reader = TextReader(
- StringIO(data), delimiter=":", header=None, on_bad_lines=2 # Skip
+ StringIO(data),
+ delimiter=":",
+ header=None,
+ on_bad_lines=2, # Skip
)
result = reader.read()
expected = {
@@ -148,7 +151,10 @@ def test_skip_bad_lines(self):
with tm.assert_produces_warning(ParserWarning, match="Skipping line"):
reader = TextReader(
- StringIO(data), delimiter=":", header=None, on_bad_lines=1 # Warn
+ StringIO(data),
+ delimiter=":",
+ header=None,
+ on_bad_lines=1, # Warn
)
reader.read()
diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py
index d93de16816725..ed5f8cde7db7b 100644
--- a/pandas/tests/io/pytables/test_file_handling.py
+++ b/pandas/tests/io/pytables/test_file_handling.py
@@ -258,7 +258,7 @@ def test_complibs_default_settings_override(tmp_path, setup_path):
@pytest.mark.filterwarnings("ignore:object name is not a valid")
@pytest.mark.skipif(
not PY311 and is_ci_environment() and is_platform_linux(),
- reason="Segfaulting in a CI environment"
+ reason="Segfaulting in a CI environment",
# with xfail, would sometimes raise UnicodeDecodeError
# invalid state byte
)
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index 607357e709b6e..6a2d460232165 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -157,7 +157,8 @@ def test_to_html_compat(self, flavor_read_html):
columns=pd.Index(list("abc"), dtype=object),
)
# pylint: disable-next=consider-using-f-string
- .map("{:.3f}".format).astype(float)
+ .map("{:.3f}".format)
+ .astype(float)
)
out = df.to_html()
res = flavor_read_html(
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index 05e1c93e1a676..cacbe0a1d6095 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -124,7 +124,8 @@ def test_is_end(self, end, tz):
)
# error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] + tm.get_locales() # type: ignore[operator]
+ "time_locale",
+ [None] + tm.get_locales(), # type: ignore[operator]
)
def test_names(self, data, time_locale):
# GH 17354
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 34465a7c12c18..911f5d7b28e3f 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -452,7 +452,8 @@ def test_dt_accessor_no_new_attributes(self):
# error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] + tm.get_locales() # type: ignore[operator]
+ "time_locale",
+ [None] + tm.get_locales(), # type: ignore[operator]
)
def test_dt_accessor_datetime_name_accessors(self, time_locale):
# Test Monday -> Sunday and January -> December, in that sequence
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index f662dfd7e2b14..25e4e1f9ec50c 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -230,7 +230,8 @@ def test_isnumeric_unicode(method, expected, any_string_dtype):
# 0x1378: ፸ ETHIOPIC NUMBER SEVENTY
# 0xFF13: 3 Em 3 # noqa: RUF003
ser = Series(
- ["A", "3", "¼", "★", "፸", "3", "four"], dtype=any_string_dtype # noqa: RUF001
+ ["A", "3", "¼", "★", "፸", "3", "four"], # noqa: RUF001
+ dtype=any_string_dtype,
)
expected_dtype = "bool" if any_string_dtype in object_pyarrow_numpy else "boolean"
expected = Series(expected, dtype=expected_dtype)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 16d684b72e1e3..02cd7b77c9b7d 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -1522,9 +1522,7 @@ def test_duplicated_with_nas(self):
]
),
np.array(["a", "b", "a", "e", "c", "b", "d", "a", "e", "f"], dtype=object),
- np.array(
- [1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64
- ),
+ np.array([1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64),
],
)
def test_numeric_object_likes(self, case):
diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py
index e675977c6fab4..f01406fb50d23 100644
--- a/pandas/tests/tseries/offsets/test_business_hour.py
+++ b/pandas/tests/tseries/offsets/test_business_hour.py
@@ -915,28 +915,34 @@ def test_apply_nanoseconds(self):
(
BusinessHour(),
{
- Timestamp("2014-07-04 15:00")
- + Nano(5): Timestamp("2014-07-04 16:00")
+ Timestamp("2014-07-04 15:00") + Nano(5): Timestamp(
+ "2014-07-04 16:00"
+ )
+ Nano(5),
- Timestamp("2014-07-04 16:00")
- + Nano(5): Timestamp("2014-07-07 09:00")
+ Timestamp("2014-07-04 16:00") + Nano(5): Timestamp(
+ "2014-07-07 09:00"
+ )
+ Nano(5),
- Timestamp("2014-07-04 16:00")
- - Nano(5): Timestamp("2014-07-04 17:00")
+ Timestamp("2014-07-04 16:00") - Nano(5): Timestamp(
+ "2014-07-04 17:00"
+ )
- Nano(5),
},
),
(
BusinessHour(-1),
{
- Timestamp("2014-07-04 15:00")
- + Nano(5): Timestamp("2014-07-04 14:00")
+ Timestamp("2014-07-04 15:00") + Nano(5): Timestamp(
+ "2014-07-04 14:00"
+ )
+ Nano(5),
- Timestamp("2014-07-04 10:00")
- + Nano(5): Timestamp("2014-07-04 09:00")
+ Timestamp("2014-07-04 10:00") + Nano(5): Timestamp(
+ "2014-07-04 09:00"
+ )
+ Nano(5),
- Timestamp("2014-07-04 10:00")
- - Nano(5): Timestamp("2014-07-03 17:00")
+ Timestamp("2014-07-04 10:00") - Nano(5): Timestamp(
+ "2014-07-03 17:00"
+ )
- Nano(5),
},
),
diff --git a/pandas/tests/tseries/offsets/test_custom_business_hour.py b/pandas/tests/tseries/offsets/test_custom_business_hour.py
index 55a184f95c2d8..0335f415e2ec2 100644
--- a/pandas/tests/tseries/offsets/test_custom_business_hour.py
+++ b/pandas/tests/tseries/offsets/test_custom_business_hour.py
@@ -269,28 +269,22 @@ def test_apply(self, apply_case):
(
CustomBusinessHour(holidays=holidays),
{
- Timestamp("2014-07-01 15:00")
- + Nano(5): Timestamp("2014-07-01 16:00")
+ Timestamp("2014-07-01 15:00") + Nano(5): Timestamp("2014-07-01 16:00")
+ Nano(5),
- Timestamp("2014-07-01 16:00")
- + Nano(5): Timestamp("2014-07-03 09:00")
+ Timestamp("2014-07-01 16:00") + Nano(5): Timestamp("2014-07-03 09:00")
+ Nano(5),
- Timestamp("2014-07-01 16:00")
- - Nano(5): Timestamp("2014-07-01 17:00")
+ Timestamp("2014-07-01 16:00") - Nano(5): Timestamp("2014-07-01 17:00")
- Nano(5),
},
),
(
CustomBusinessHour(-1, holidays=holidays),
{
- Timestamp("2014-07-01 15:00")
- + Nano(5): Timestamp("2014-07-01 14:00")
+ Timestamp("2014-07-01 15:00") + Nano(5): Timestamp("2014-07-01 14:00")
+ Nano(5),
- Timestamp("2014-07-01 10:00")
- + Nano(5): Timestamp("2014-07-01 09:00")
+ Timestamp("2014-07-01 10:00") + Nano(5): Timestamp("2014-07-01 09:00")
+ Nano(5),
- Timestamp("2014-07-01 10:00")
- - Nano(5): Timestamp("2014-06-26 17:00")
+ Timestamp("2014-07-01 10:00") - Nano(5): Timestamp("2014-06-26 17:00")
- Nano(5),
},
),
diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py
index 3c429a960b451..646284c79a3ad 100644
--- a/pandas/tseries/holiday.py
+++ b/pandas/tseries/holiday.py
@@ -484,9 +484,7 @@ def holidays(self, start=None, end=None, return_name: bool = False):
else:
# error: Incompatible types in assignment (expression has type
# "Series", variable has type "DataFrame")
- holidays = Series(
- index=DatetimeIndex([]), dtype=object
- ) # type: ignore[assignment]
+ holidays = Series(index=DatetimeIndex([]), dtype=object) # type: ignore[assignment]
self._cache = (start, end, holidays.sort_index())
diff --git a/pyproject.toml b/pyproject.toml
index 5aaa06d9a8da1..f693048adb60c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -188,27 +188,6 @@ test-command = ""
select = "*-macosx*"
environment = {CFLAGS="-g0"}
-[tool.black]
-target-version = ['py39', 'py310']
-required-version = '23.11.0'
-exclude = '''
-(
- asv_bench/env
- | \.egg
- | \.git
- | \.hg
- | \.mypy_cache
- | \.nox
- | \.tox
- | \.venv
- | _build
- | buck-out
- | build
- | dist
- | setup.py
-)
-'''
-
[tool.ruff]
line-length = 88
target-version = "py310"
@@ -325,6 +304,8 @@ ignore = [
"PERF102",
# try-except-in-loop, becomes useless in Python 3.11
"PERF203",
+ # The following rules may cause conflicts when used with the formatter:
+ "ISC001",
### TODO: Enable gradually
diff --git a/scripts/tests/data/deps_minimum.toml b/scripts/tests/data/deps_minimum.toml
index 3be6be17d1ee2..0424920e5f446 100644
--- a/scripts/tests/data/deps_minimum.toml
+++ b/scripts/tests/data/deps_minimum.toml
@@ -161,26 +161,6 @@ test-command = ""
select = "*-win32"
environment = { IS_32_BIT="true" }
-[tool.black]
-target-version = ['py38', 'py39']
-exclude = '''
-(
- asv_bench/env
- | \.egg
- | \.git
- | \.hg
- | \.mypy_cache
- | \.nox
- | \.tox
- | \.venv
- | _build
- | buck-out
- | build
- | dist
- | setup.py
-)
-'''
-
[tool.ruff]
line-length = 88
update-check = false
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56704 | 2024-01-02T22:23:12Z | 2024-01-04T00:49:24Z | 2024-01-04T00:49:24Z | 2024-01-04T00:51:12Z |
DOC: Corrected typo in warning on coerce | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 51b4c4f297b07..d4eb5742ef928 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -432,7 +432,7 @@ In a future version, these will raise an error and you should cast to a common d
In [3]: ser[0] = 'not an int64'
FutureWarning:
- Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas.
+ Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas.
Value 'not an int64' has dtype incompatible with int64, please explicitly cast to a compatible dtype first.
In [4]: ser
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 20eff9315bc80..b7af545bd523e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -512,7 +512,7 @@ def coerce_to_target_dtype(self, other, warn_on_upcast: bool = False) -> Block:
if warn_on_upcast:
warnings.warn(
f"Setting an item of incompatible dtype is deprecated "
- "and will raise in a future error of pandas. "
+ "and will raise an error in a future version of pandas. "
f"Value '{other}' has dtype incompatible with {self.values.dtype}, "
"please explicitly cast to a compatible dtype first.",
FutureWarning,
| Low priority.
I encountered this warning message:
> "Setting an item of incompatible dtype is deprecated and will raise in a future **error** of pandas."
Which I believe should read:
> "Setting an item of incompatible dtype is deprecated and will raise **an error** in a future **version** of pandas." | https://api.github.com/repos/pandas-dev/pandas/pulls/56699 | 2024-01-02T20:44:54Z | 2024-01-03T21:37:12Z | 2024-01-03T21:37:12Z | 2024-01-03T21:42:25Z |
Backport PR #56167 on branch 2.2.x ([ENH]: Expand types allowed in Series.struct.field) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 649ad37a56b35..15e98cbb2a4d7 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -251,6 +251,14 @@ DataFrame. (:issue:`54938`)
)
series.struct.explode()
+Use :meth:`Series.struct.field` to index into a (possible nested)
+struct field.
+
+
+.. ipython:: python
+
+ series.struct.field("project")
+
.. _whatsnew_220.enhancements.list_accessor:
Series.list accessor for PyArrow list data
diff --git a/pandas/core/arrays/arrow/accessors.py b/pandas/core/arrays/arrow/accessors.py
index 7f88267943526..124f8fb6ad8bc 100644
--- a/pandas/core/arrays/arrow/accessors.py
+++ b/pandas/core/arrays/arrow/accessors.py
@@ -6,13 +6,18 @@
ABCMeta,
abstractmethod,
)
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ cast,
+)
from pandas.compat import (
pa_version_under10p1,
pa_version_under11p0,
)
+from pandas.core.dtypes.common import is_list_like
+
if not pa_version_under10p1:
import pyarrow as pa
import pyarrow.compute as pc
@@ -267,15 +272,27 @@ def dtypes(self) -> Series:
names = [struct.name for struct in pa_type]
return Series(types, index=Index(names))
- def field(self, name_or_index: str | int) -> Series:
+ def field(
+ self,
+ name_or_index: list[str]
+ | list[bytes]
+ | list[int]
+ | pc.Expression
+ | bytes
+ | str
+ | int,
+ ) -> Series:
"""
Extract a child field of a struct as a Series.
Parameters
----------
- name_or_index : str | int
+ name_or_index : str | bytes | int | expression | list
Name or index of the child field to extract.
+ For list-like inputs, this will index into a nested
+ struct.
+
Returns
-------
pandas.Series
@@ -285,6 +302,19 @@ def field(self, name_or_index: str | int) -> Series:
--------
Series.struct.explode : Return all child fields as a DataFrame.
+ Notes
+ -----
+ The name of the resulting Series will be set using the following
+ rules:
+
+ - For string, bytes, or integer `name_or_index` (or a list of these, for
+ a nested selection), the Series name is set to the selected
+ field's name.
+ - For a :class:`pyarrow.compute.Expression`, this is set to
+ the string form of the expression.
+ - For list-like `name_or_index`, the name will be set to the
+ name of the final field selected.
+
Examples
--------
>>> import pyarrow as pa
@@ -314,27 +344,92 @@ def field(self, name_or_index: str | int) -> Series:
1 2
2 1
Name: version, dtype: int64[pyarrow]
+
+ Or an expression
+
+ >>> import pyarrow.compute as pc
+ >>> s.struct.field(pc.field("project"))
+ 0 pandas
+ 1 pandas
+ 2 numpy
+ Name: project, dtype: string[pyarrow]
+
+ For nested struct types, you can pass a list of values to index
+ multiple levels:
+
+ >>> version_type = pa.struct([
+ ... ("major", pa.int64()),
+ ... ("minor", pa.int64()),
+ ... ])
+ >>> s = pd.Series(
+ ... [
+ ... {"version": {"major": 1, "minor": 5}, "project": "pandas"},
+ ... {"version": {"major": 2, "minor": 1}, "project": "pandas"},
+ ... {"version": {"major": 1, "minor": 26}, "project": "numpy"},
+ ... ],
+ ... dtype=pd.ArrowDtype(pa.struct(
+ ... [("version", version_type), ("project", pa.string())]
+ ... ))
+ ... )
+ >>> s.struct.field(["version", "minor"])
+ 0 5
+ 1 1
+ 2 26
+ Name: minor, dtype: int64[pyarrow]
+ >>> s.struct.field([0, 0])
+ 0 1
+ 1 2
+ 2 1
+ Name: major, dtype: int64[pyarrow]
"""
from pandas import Series
+ def get_name(
+ level_name_or_index: list[str]
+ | list[bytes]
+ | list[int]
+ | pc.Expression
+ | bytes
+ | str
+ | int,
+ data: pa.ChunkedArray,
+ ):
+ if isinstance(level_name_or_index, int):
+ name = data.type.field(level_name_or_index).name
+ elif isinstance(level_name_or_index, (str, bytes)):
+ name = level_name_or_index
+ elif isinstance(level_name_or_index, pc.Expression):
+ name = str(level_name_or_index)
+ elif is_list_like(level_name_or_index):
+ # For nested input like [2, 1, 2]
+ # iteratively get the struct and field name. The last
+ # one is used for the name of the index.
+ level_name_or_index = list(reversed(level_name_or_index))
+ selected = data
+ while level_name_or_index:
+ # we need the cast, otherwise mypy complains about
+ # getting ints, bytes, or str here, which isn't possible.
+ level_name_or_index = cast(list, level_name_or_index)
+ name_or_index = level_name_or_index.pop()
+ name = get_name(name_or_index, selected)
+ selected = selected.type.field(selected.type.get_field_index(name))
+ name = selected.name
+ else:
+ raise ValueError(
+ "name_or_index must be an int, str, bytes, "
+ "pyarrow.compute.Expression, or list of those"
+ )
+ return name
+
pa_arr = self._data.array._pa_array
- if isinstance(name_or_index, int):
- index = name_or_index
- elif isinstance(name_or_index, str):
- index = pa_arr.type.get_field_index(name_or_index)
- else:
- raise ValueError(
- "name_or_index must be an int or str, "
- f"got {type(name_or_index).__name__}"
- )
+ name = get_name(name_or_index, pa_arr)
+ field_arr = pc.struct_field(pa_arr, name_or_index)
- pa_field = pa_arr.type[index]
- field_arr = pc.struct_field(pa_arr, [index])
return Series(
field_arr,
dtype=ArrowDtype(field_arr.type),
index=self._data.index,
- name=pa_field.name,
+ name=name,
)
def explode(self) -> DataFrame:
diff --git a/pandas/tests/series/accessors/test_struct_accessor.py b/pandas/tests/series/accessors/test_struct_accessor.py
index 1ec5b3b726d17..80aea75fda406 100644
--- a/pandas/tests/series/accessors/test_struct_accessor.py
+++ b/pandas/tests/series/accessors/test_struct_accessor.py
@@ -2,6 +2,11 @@
import pytest
+from pandas.compat.pyarrow import (
+ pa_version_under11p0,
+ pa_version_under13p0,
+)
+
from pandas import (
ArrowDtype,
DataFrame,
@@ -11,6 +16,7 @@
import pandas._testing as tm
pa = pytest.importorskip("pyarrow")
+pc = pytest.importorskip("pyarrow.compute")
def test_struct_accessor_dtypes():
@@ -53,6 +59,7 @@ def test_struct_accessor_dtypes():
tm.assert_series_equal(actual, expected)
+@pytest.mark.skipif(pa_version_under13p0, reason="pyarrow>=13.0.0 required")
def test_struct_accessor_field():
index = Index([-100, 42, 123])
ser = Series(
@@ -94,10 +101,11 @@ def test_struct_accessor_field():
def test_struct_accessor_field_with_invalid_name_or_index():
ser = Series([], dtype=ArrowDtype(pa.struct([("field", pa.int64())])))
- with pytest.raises(ValueError, match="name_or_index must be an int or str"):
+ with pytest.raises(ValueError, match="name_or_index must be an int, str,"):
ser.struct.field(1.1)
+@pytest.mark.skipif(pa_version_under11p0, reason="pyarrow>=11.0.0 required")
def test_struct_accessor_explode():
index = Index([-100, 42, 123])
ser = Series(
@@ -148,3 +156,41 @@ def test_struct_accessor_api_for_invalid(invalid):
),
):
invalid.struct
+
+
+@pytest.mark.parametrize(
+ ["indices", "name"],
+ [
+ (0, "int_col"),
+ ([1, 2], "str_col"),
+ (pc.field("int_col"), "int_col"),
+ ("int_col", "int_col"),
+ (b"string_col", b"string_col"),
+ ([b"string_col"], "string_col"),
+ ],
+)
+@pytest.mark.skipif(pa_version_under13p0, reason="pyarrow>=13.0.0 required")
+def test_struct_accessor_field_expanded(indices, name):
+ arrow_type = pa.struct(
+ [
+ ("int_col", pa.int64()),
+ (
+ "struct_col",
+ pa.struct(
+ [
+ ("int_col", pa.int64()),
+ ("float_col", pa.float64()),
+ ("str_col", pa.string()),
+ ]
+ ),
+ ),
+ (b"string_col", pa.string()),
+ ]
+ )
+
+ data = pa.array([], type=arrow_type)
+ ser = Series(data, dtype=ArrowDtype(arrow_type))
+ expected = pc.struct_field(data, indices)
+ result = ser.struct.field(indices)
+ tm.assert_equal(result.array._pa_array.combine_chunks(), expected)
+ assert result.name == name
| Backport PR #56167: [ENH]: Expand types allowed in Series.struct.field | https://api.github.com/repos/pandas-dev/pandas/pulls/56698 | 2024-01-02T19:16:37Z | 2024-01-02T20:39:07Z | 2024-01-02T20:39:07Z | 2024-01-02T20:39:07Z |
[pre-commit.ci] pre-commit autoupdate | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 4b02ad7cf886f..34386c6042077 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -20,11 +20,11 @@ ci:
repos:
- repo: https://github.com/hauntsaninja/black-pre-commit-mirror
# black compiled with mypyc
- rev: 23.11.0
+ rev: 23.12.1
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.1.6
+ rev: v0.1.9
hooks:
- id: ruff
args: [--exit-non-zero-on-fix]
@@ -73,7 +73,7 @@ repos:
args: [--remove]
- id: trailing-whitespace
- repo: https://github.com/pylint-dev/pylint
- rev: v3.0.1
+ rev: v3.0.3
hooks:
- id: pylint
stages: [manual]
@@ -92,7 +92,7 @@ repos:
args: [--disable=all, --enable=redefined-outer-name]
stages: [manual]
- repo: https://github.com/PyCQA/isort
- rev: 5.12.0
+ rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/asottile/pyupgrade
diff --git a/pyproject.toml b/pyproject.toml
index 5aaa06d9a8da1..426f331dc5ed3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -190,7 +190,7 @@ environment = {CFLAGS="-g0"}
[tool.black]
target-version = ['py39', 'py310']
-required-version = '23.11.0'
+required-version = '23.12.1'
exclude = '''
(
asv_bench/env
| <!--pre-commit.ci start-->
updates:
- [github.com/hauntsaninja/black-pre-commit-mirror: 23.11.0 → 23.12.1](https://github.com/hauntsaninja/black-pre-commit-mirror/compare/23.11.0...23.12.1)
- [github.com/astral-sh/ruff-pre-commit: v0.1.6 → v0.1.9](https://github.com/astral-sh/ruff-pre-commit/compare/v0.1.6...v0.1.9)
- [github.com/pylint-dev/pylint: v3.0.1 → v3.0.3](https://github.com/pylint-dev/pylint/compare/v3.0.1...v3.0.3)
- [github.com/PyCQA/isort: 5.12.0 → 5.13.2](https://github.com/PyCQA/isort/compare/5.12.0...5.13.2)
<!--pre-commit.ci end--> | https://api.github.com/repos/pandas-dev/pandas/pulls/56695 | 2024-01-01T16:29:34Z | 2024-01-08T21:22:44Z | null | 2024-01-08T21:22:52Z |
implement mod and divmod for pyarrow types | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..e0507991d82ad 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -777,6 +777,7 @@ Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
+- Bug in :meth:`Series.__mod__` and :meth:`Series.__divmod__` for :class:`ArrowDtype` raising ``NotImplementedError`` (:issue:`56693`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
Conversion
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..e398c330467de 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -135,6 +135,18 @@ def floordiv_compat(
result = result.cast(left.type)
return result
+ def divmod_compat(
+ left: pa.ChunkedArray | pa.Array | pa.Scalar,
+ right: pa.ChunkedArray | pa.Array | pa.Scalar,
+ ) -> tuple[pa.ChunkedArray, pa.ChunkedArray]:
+ # (x % y) = x - (x // y) * y
+ # TODO: Should be replaced with corresponding arrow compute
+ # method when available
+ # https://lists.apache.org/thread/h3t6nz1ys2k2hnbrjvwyoxkf70cps8sh
+ floordiv_result = floordiv_compat(left, right)
+ modulus_result = pc.subtract(left, pc.multiply(floordiv_result, right))
+ return floordiv_result, modulus_result
+
ARROW_ARITHMETIC_FUNCS = {
"add": pc.add_checked,
"radd": lambda x, y: pc.add_checked(y, x),
@@ -146,10 +158,10 @@ def floordiv_compat(
"rtruediv": lambda x, y: pc.divide(y, cast_for_truediv(x, y)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
- "mod": NotImplemented,
- "rmod": NotImplemented,
- "divmod": NotImplemented,
- "rdivmod": NotImplemented,
+ "mod": lambda x, y: divmod_compat(x, y)[1],
+ "rmod": lambda x, y: divmod_compat(y, x)[1],
+ "divmod": lambda x, y: divmod_compat(x, y),
+ "rdivmod": lambda x, y: divmod_compat(y, x),
"pow": pc.power_checked,
"rpow": lambda x, y: pc.power_checked(y, x),
}
@@ -750,6 +762,8 @@ def _evaluate_op_method(self, other, op, arrow_funcs):
raise NotImplementedError(f"{op.__name__} not implemented.")
result = pc_func(self._pa_array, other)
+ if op is divmod or op is roperator.rdivmod:
+ return type(self)(result[0]), type(self)(result[1])
return type(self)(result)
def _logical_method(self, other, op):
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..15238213f5f52 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3238,6 +3238,75 @@ def test_arrow_floordiv():
tm.assert_series_equal(result, expected)
+modulus_test_cases = [
+ [-7, 3],
+ [-7, -4],
+ [-7, -8],
+ [-7, 8],
+ [7, 8],
+ [7, 3],
+ [7, -3],
+ [-1.2, 1.3],
+ [1.2, 1.3],
+ [-1.2, -1.3],
+ [-1.2, 0.5],
+ [1.2, 0.5],
+ [-1.2, -0.5],
+]
+
+
+@pytest.mark.parametrize("left, right", modulus_test_cases)
+def test_arrow_modulus(left, right):
+ # GH 56693
+ dtype = "int64[pyarrow]" if isinstance(left, int) else "double[pyarrow]"
+ a = pd.Series([left], dtype=dtype)
+ b = pd.Series([right], dtype=dtype)
+ result = a % b
+ # Use stdlib python modulus to baseline.
+ expected = pd.Series([left % right], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("left, right", modulus_test_cases)
+def test_arrow_reflected_modulus(left, right):
+ # GH 56693
+ dtype = "int64[pyarrow]" if isinstance(left, int) else "double[pyarrow]"
+ a = pd.Series([left], dtype=dtype)
+ result = right % a
+ # Use stdlib python modulus to baseline.
+ expected = pd.Series([right % left], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("left, right", modulus_test_cases)
+def test_arrow_divmod(left, right):
+ # GH 56693
+ dtype = "int64[pyarrow]" if isinstance(left, int) else "double[pyarrow]"
+ a = pd.Series([left], dtype=dtype)
+ b = pd.Series([right], dtype=dtype)
+ result_floordiv, result_modulus = divmod(a, b)
+ # Use stdlib python modulus to baseline.
+ stdlib_baseline = divmod(left, right)
+ expected_floordiv = pd.Series([stdlib_baseline[0]], dtype=dtype)
+ expected_modulus = pd.Series([stdlib_baseline[1]], dtype=dtype)
+ tm.assert_series_equal(result_floordiv, expected_floordiv)
+ tm.assert_series_equal(result_modulus, expected_modulus)
+
+
+@pytest.mark.parametrize("left, right", modulus_test_cases)
+def test_arrow_reflected_divmod(left, right):
+ # GH 56693
+ dtype = "int64[pyarrow]" if isinstance(left, int) else "double[pyarrow]"
+ a = pd.Series([left], dtype=dtype)
+ result_floordiv, result_modulus = divmod(right, a)
+ # Use stdlib python modulus to baseline.
+ stdlib_baseline = divmod(right, left)
+ expected_floordiv = pd.Series([stdlib_baseline[0]], dtype=dtype)
+ expected_modulus = pd.Series([stdlib_baseline[1]], dtype=dtype)
+ tm.assert_series_equal(result_floordiv, expected_floordiv)
+ tm.assert_series_equal(result_modulus, expected_modulus)
+
+
def test_arrow_floordiv_large_values():
# GH 55561
a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
| - [ ] closes #56693(Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56694 | 2024-01-01T06:30:56Z | 2024-01-01T06:51:44Z | null | 2024-01-01T06:51:45Z |
Bug pyarrow implementation of str.fullmatch matches partial string. issue #56652 | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 15e98cbb2a4d7..043646457f604 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -805,6 +805,7 @@ Strings
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56404`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for :class:`ArrowDtype` with ``pyarrow.string`` dtype (:issue:`56579`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for ``string[pyarrow]`` (:issue:`54942`)
+- Bug in :meth:`str.fullmatch` when ``dtype=pandas.ArrowDtype(pyarrow.string()))`` allows partial matches when regex ends in literal //$ (:issue:`56652`)
- Bug in comparison operations for ``dtype="string[pyarrow_numpy]"`` raising if dtypes can't be compared (:issue:`56008`)
Interval
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index d7c4d695e6951..ce496d612ae46 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -2296,7 +2296,7 @@ def _str_match(
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
) -> Self:
- if not pat.endswith("$") or pat.endswith("//$"):
+ if not pat.endswith("$") or pat.endswith("\\$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index cb07fcf1a48fa..8c8787d15c8fe 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -436,7 +436,7 @@ def _str_match(
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
):
- if not pat.endswith("$") or pat.endswith("//$"):
+ if not pat.endswith("$") or pat.endswith("\\$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 76982ee5c38f8..204084d3a2de0 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -1898,16 +1898,21 @@ def test_str_match(pat, case, na, exp):
@pytest.mark.parametrize(
"pat, case, na, exp",
[
- ["abc", False, None, [True, None]],
- ["Abc", True, None, [False, None]],
- ["bc", True, None, [False, None]],
- ["ab", False, True, [True, True]],
- ["a[a-z]{2}", False, None, [True, None]],
- ["A[a-z]{1}", True, None, [False, None]],
+ ["abc", False, None, [True, True, False, None]],
+ ["Abc", True, None, [False, False, False, None]],
+ ["bc", True, None, [False, False, False, None]],
+ ["ab", False, None, [True, True, False, None]],
+ ["a[a-z]{2}", False, None, [True, True, False, None]],
+ ["A[a-z]{1}", True, None, [False, False, False, None]],
+ # GH Issue: #56652
+ ["abc$", False, None, [True, False, False, None]],
+ ["abc\\$", False, None, [False, True, False, None]],
+ ["Abc$", True, None, [False, False, False, None]],
+ ["Abc\\$", True, None, [False, False, False, None]],
],
)
def test_str_fullmatch(pat, case, na, exp):
- ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
+ ser = pd.Series(["abc", "abc$", "$abc", None], dtype=ArrowDtype(pa.string()))
result = ser.str.match(pat, case=case, na=na)
expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 3f58c6d703f8f..cd4707ac405de 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -730,6 +730,15 @@ def test_fullmatch(any_string_dtype):
tm.assert_series_equal(result, expected)
+def test_fullmatch_dollar_literal(any_string_dtype):
+ # GH 56652
+ ser = Series(["foo", "foo$foo", np.nan, "foo$"], dtype=any_string_dtype)
+ result = ser.str.fullmatch("foo\\$")
+ expected_dtype = "object" if any_string_dtype in object_pyarrow_numpy else "boolean"
+ expected = Series([False, False, np.nan, True], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
def test_fullmatch_na_kwarg(any_string_dtype):
ser = Series(
["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
| - [x] closes #56652
- [x] Tests updated and passed
- [x] All code checks passed
Changed array.py: Makes Series(["abc$abc]).str.fullmatch("abc\\$") give the same result as when dtype = pyarrow.string as opposed to dtype = str.
Issue reporter (Issue-[#56652](https://github.com/pandas-dev/pandas/issues/56652)) requested change "//$" to "\\$", but this resulted in DepreciationWarnng in pytest, so used "\\\\$" instead.
Change test_arrow.py: updated test_str_fullmatch to account for edge cases where string starts with and ends with literal $ as well as ends with the string.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56691 | 2023-12-31T15:18:41Z | 2024-01-03T18:41:23Z | 2024-01-03T18:41:23Z | 2024-01-17T22:28:22Z |
TYP: mostly Hashtable and ArrowExtensionArray | diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi
index 555ec73acd9b2..3bb957812f0ed 100644
--- a/pandas/_libs/hashtable.pyi
+++ b/pandas/_libs/hashtable.pyi
@@ -2,6 +2,7 @@ from typing import (
Any,
Hashable,
Literal,
+ overload,
)
import numpy as np
@@ -180,18 +181,30 @@ class HashTable:
na_value: object = ...,
mask=...,
) -> npt.NDArray[np.intp]: ...
+ @overload
def unique(
self,
values: np.ndarray, # np.ndarray[subclass-specific]
- return_inverse: bool = ...,
- mask=...,
- ) -> (
- tuple[
- np.ndarray, # np.ndarray[subclass-specific]
- npt.NDArray[np.intp],
- ]
- | np.ndarray
- ): ... # np.ndarray[subclass-specific]
+ *,
+ return_inverse: Literal[False] = ...,
+ mask: None = ...,
+ ) -> np.ndarray: ... # np.ndarray[subclass-specific]
+ @overload
+ def unique(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ *,
+ return_inverse: Literal[True],
+ mask: None = ...,
+ ) -> tuple[np.ndarray, npt.NDArray[np.intp],]: ... # np.ndarray[subclass-specific]
+ @overload
+ def unique(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ *,
+ return_inverse: Literal[False] = ...,
+ mask: npt.NDArray[np.bool_],
+ ) -> tuple[np.ndarray, npt.NDArray[np.bool_],]: ... # np.ndarray[subclass-specific]
def factorize(
self,
values: np.ndarray, # np.ndarray[subclass-specific]
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index c0723392496c1..ed1284c34e110 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -755,7 +755,7 @@ cdef class {{name}}HashTable(HashTable):
return uniques.to_array(), result_mask.to_array()
return uniques.to_array()
- def unique(self, const {{dtype}}_t[:] values, bint return_inverse=False, object mask=None):
+ def unique(self, const {{dtype}}_t[:] values, *, bint return_inverse=False, object mask=None):
"""
Calculate unique values and labels (no sorting!)
@@ -1180,7 +1180,7 @@ cdef class StringHashTable(HashTable):
return uniques.to_array(), labels.base # .base -> underlying ndarray
return uniques.to_array()
- def unique(self, ndarray[object] values, bint return_inverse=False, object mask=None):
+ def unique(self, ndarray[object] values, *, bint return_inverse=False, object mask=None):
"""
Calculate unique values and labels (no sorting!)
@@ -1438,7 +1438,7 @@ cdef class PyObjectHashTable(HashTable):
return uniques.to_array(), labels.base # .base -> underlying ndarray
return uniques.to_array()
- def unique(self, ndarray[object] values, bint return_inverse=False, object mask=None):
+ def unique(self, ndarray[object] values, *, bint return_inverse=False, object mask=None):
"""
Calculate unique values and labels (no sorting!)
diff --git a/pandas/_typing.py b/pandas/_typing.py
index 3df9a47a35fca..a80f9603493a7 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -109,6 +109,7 @@
# array-like
ArrayLike = Union["ExtensionArray", np.ndarray]
+ArrayLikeT = TypeVar("ArrayLikeT", "ExtensionArray", np.ndarray)
AnyArrayLike = Union[ArrayLike, "Index", "Series"]
TimeArrayLike = Union["DatetimeArray", "TimedeltaArray"]
@@ -137,7 +138,7 @@ def __len__(self) -> int:
def __iter__(self) -> Iterator[_T_co]:
...
- def index(self, value: Any, /, start: int = 0, stop: int = ...) -> int:
+ def index(self, value: Any, start: int = ..., stop: int = ..., /) -> int:
...
def count(self, value: Any, /) -> int:
diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index cd98087c06c18..ff589ebba4cf6 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -7,7 +7,10 @@
import copy
import io
import pickle as pkl
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
import numpy as np
@@ -209,7 +212,7 @@ def load_newobj_ex(self) -> None:
pass
-def load(fh, encoding: str | None = None, is_verbose: bool = False):
+def load(fh, encoding: str | None = None, is_verbose: bool = False) -> Any:
"""
Load a pickle, with a provided encoding,
@@ -239,7 +242,7 @@ def loads(
fix_imports: bool = True,
encoding: str = "ASCII",
errors: str = "strict",
-):
+) -> Any:
"""
Analogous to pickle._loads.
"""
diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py
index 698abb2ec4989..9098a6f9664a9 100644
--- a/pandas/core/accessor.py
+++ b/pandas/core/accessor.py
@@ -54,7 +54,7 @@ class PandasDelegate:
def _delegate_property_get(self, name: str, *args, **kwargs):
raise TypeError(f"You cannot access the property {name}")
- def _delegate_property_set(self, name: str, value, *args, **kwargs):
+ def _delegate_property_set(self, name: str, value, *args, **kwargs) -> None:
raise TypeError(f"The property {name} cannot be set")
def _delegate_method(self, name: str, *args, **kwargs):
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 15a07da76d2f7..76fdcefd03407 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -25,6 +25,7 @@
from pandas._typing import (
AnyArrayLike,
ArrayLike,
+ ArrayLikeT,
AxisInt,
DtypeObj,
TakeIndexer,
@@ -182,8 +183,8 @@ def _ensure_data(values: ArrayLike) -> np.ndarray:
def _reconstruct_data(
- values: ArrayLike, dtype: DtypeObj, original: AnyArrayLike
-) -> ArrayLike:
+ values: ArrayLikeT, dtype: DtypeObj, original: AnyArrayLike
+) -> ArrayLikeT:
"""
reverse of _ensure_data
@@ -206,7 +207,9 @@ def _reconstruct_data(
# that values.dtype == dtype
cls = dtype.construct_array_type()
- values = cls._from_sequence(values, dtype=dtype)
+ # error: Incompatible types in assignment (expression has type
+ # "ExtensionArray", variable has type "ndarray[Any, Any]")
+ values = cls._from_sequence(values, dtype=dtype) # type: ignore[assignment]
else:
values = values.astype(dtype, copy=False)
@@ -259,7 +262,9 @@ def _ensure_arraylike(values, func_name: str) -> ArrayLike:
}
-def _get_hashtable_algo(values: np.ndarray):
+def _get_hashtable_algo(
+ values: np.ndarray,
+) -> tuple[type[htable.HashTable], np.ndarray]:
"""
Parameters
----------
@@ -1550,7 +1555,9 @@ def safe_sort(
hash_klass, values = _get_hashtable_algo(values) # type: ignore[arg-type]
t = hash_klass(len(values))
t.map_locations(values)
- sorter = ensure_platform_int(t.lookup(ordered))
+ # error: Argument 1 to "lookup" of "HashTable" has incompatible type
+ # "ExtensionArray | ndarray[Any, Any] | Index | Series"; expected "ndarray"
+ sorter = ensure_platform_int(t.lookup(ordered)) # type: ignore[arg-type]
if use_na_sentinel:
# take_nd is faster, but only works for na_sentinels of -1
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..d7c4d695e6951 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -10,6 +10,7 @@
Callable,
Literal,
cast,
+ overload,
)
import unicodedata
@@ -157,6 +158,7 @@ def floordiv_compat(
if TYPE_CHECKING:
from collections.abc import Sequence
+ from pandas._libs.missing import NAType
from pandas._typing import (
ArrayLike,
AxisInt,
@@ -280,7 +282,9 @@ def __init__(self, values: pa.Array | pa.ChunkedArray) -> None:
self._dtype = ArrowDtype(self._pa_array.type)
@classmethod
- def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+ def _from_sequence(
+ cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
+ ) -> Self:
"""
Construct a new ExtensionArray from a sequence of scalars.
"""
@@ -292,7 +296,7 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: Dtype | None = None, copy: bool = False
- ):
+ ) -> Self:
"""
Construct a new ExtensionArray from a sequence of strings.
"""
@@ -675,7 +679,7 @@ def __setstate__(self, state) -> None:
state["_pa_array"] = pa.chunked_array(data)
self.__dict__.update(state)
- def _cmp_method(self, other, op):
+ def _cmp_method(self, other, op) -> ArrowExtensionArray:
pc_func = ARROW_CMP_FUNCS[op.__name__]
if isinstance(
other, (ArrowExtensionArray, np.ndarray, list, BaseMaskedArray)
@@ -701,7 +705,7 @@ def _cmp_method(self, other, op):
)
return ArrowExtensionArray(result)
- def _evaluate_op_method(self, other, op, arrow_funcs):
+ def _evaluate_op_method(self, other, op, arrow_funcs) -> Self:
pa_type = self._pa_array.type
other = self._box_pa(other)
@@ -752,7 +756,7 @@ def _evaluate_op_method(self, other, op, arrow_funcs):
result = pc_func(self._pa_array, other)
return type(self)(result)
- def _logical_method(self, other, op):
+ def _logical_method(self, other, op) -> Self:
# For integer types `^`, `|`, `&` are bitwise operators and return
# integer types. Otherwise these are boolean ops.
if pa.types.is_integer(self._pa_array.type):
@@ -760,7 +764,7 @@ def _logical_method(self, other, op):
else:
return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS)
- def _arith_method(self, other, op):
+ def _arith_method(self, other, op) -> Self:
return self._evaluate_op_method(other, op, ARROW_ARITHMETIC_FUNCS)
def equals(self, other) -> bool:
@@ -825,7 +829,15 @@ def isna(self) -> npt.NDArray[np.bool_]:
return self._pa_array.is_null().to_numpy()
- def any(self, *, skipna: bool = True, **kwargs):
+ @overload
+ def any(self, *, skipna: Literal[True] = ..., **kwargs) -> bool:
+ ...
+
+ @overload
+ def any(self, *, skipna: bool, **kwargs) -> bool | NAType:
+ ...
+
+ def any(self, *, skipna: bool = True, **kwargs) -> bool | NAType:
"""
Return whether any element is truthy.
@@ -883,7 +895,15 @@ def any(self, *, skipna: bool = True, **kwargs):
"""
return self._reduce("any", skipna=skipna, **kwargs)
- def all(self, *, skipna: bool = True, **kwargs):
+ @overload
+ def all(self, *, skipna: Literal[True] = ..., **kwargs) -> bool:
+ ...
+
+ @overload
+ def all(self, *, skipna: bool, **kwargs) -> bool | NAType:
+ ...
+
+ def all(self, *, skipna: bool = True, **kwargs) -> bool | NAType:
"""
Return whether all elements are truthy.
@@ -2027,7 +2047,7 @@ def _if_else(
cond: npt.NDArray[np.bool_] | bool,
left: ArrayLike | Scalar,
right: ArrayLike | Scalar,
- ):
+ ) -> pa.Array:
"""
Choose values based on a condition.
@@ -2071,7 +2091,7 @@ def _replace_with_mask(
values: pa.Array | pa.ChunkedArray,
mask: npt.NDArray[np.bool_] | bool,
replacements: ArrayLike | Scalar,
- ):
+ ) -> pa.Array | pa.ChunkedArray:
"""
Replace items selected with a mask.
@@ -2178,14 +2198,14 @@ def _apply_elementwise(self, func: Callable) -> list[list[Any]]:
for chunk in self._pa_array.iterchunks()
]
- def _str_count(self, pat: str, flags: int = 0):
+ def _str_count(self, pat: str, flags: int = 0) -> Self:
if flags:
raise NotImplementedError(f"count not implemented with {flags=}")
return type(self)(pc.count_substring_regex(self._pa_array, pat))
def _str_contains(
self, pat, case: bool = True, flags: int = 0, na=None, regex: bool = True
- ):
+ ) -> Self:
if flags:
raise NotImplementedError(f"contains not implemented with {flags=}")
@@ -2198,7 +2218,7 @@ def _str_contains(
result = result.fill_null(na)
return type(self)(result)
- def _str_startswith(self, pat: str | tuple[str, ...], na=None):
+ def _str_startswith(self, pat: str | tuple[str, ...], na=None) -> Self:
if isinstance(pat, str):
result = pc.starts_with(self._pa_array, pattern=pat)
else:
@@ -2215,7 +2235,7 @@ def _str_startswith(self, pat: str | tuple[str, ...], na=None):
result = result.fill_null(na)
return type(self)(result)
- def _str_endswith(self, pat: str | tuple[str, ...], na=None):
+ def _str_endswith(self, pat: str | tuple[str, ...], na=None) -> Self:
if isinstance(pat, str):
result = pc.ends_with(self._pa_array, pattern=pat)
else:
@@ -2240,7 +2260,7 @@ def _str_replace(
case: bool = True,
flags: int = 0,
regex: bool = True,
- ):
+ ) -> Self:
if isinstance(pat, re.Pattern) or callable(repl) or not case or flags:
raise NotImplementedError(
"replace is not supported with a re.Pattern, callable repl, "
@@ -2259,29 +2279,28 @@ def _str_replace(
)
return type(self)(result)
- def _str_repeat(self, repeats: int | Sequence[int]):
+ def _str_repeat(self, repeats: int | Sequence[int]) -> Self:
if not isinstance(repeats, int):
raise NotImplementedError(
f"repeat is not implemented when repeats is {type(repeats).__name__}"
)
- else:
- return type(self)(pc.binary_repeat(self._pa_array, repeats))
+ return type(self)(pc.binary_repeat(self._pa_array, repeats))
def _str_match(
self, pat: str, case: bool = True, flags: int = 0, na: Scalar | None = None
- ):
+ ) -> Self:
if not pat.startswith("^"):
pat = f"^{pat}"
return self._str_contains(pat, case, flags, na, regex=True)
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
- ):
+ ) -> Self:
if not pat.endswith("$") or pat.endswith("//$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
- def _str_find(self, sub: str, start: int = 0, end: int | None = None):
+ def _str_find(self, sub: str, start: int = 0, end: int | None = None) -> Self:
if start != 0 and end is not None:
slices = pc.utf8_slice_codeunits(self._pa_array, start, stop=end)
result = pc.find_substring(slices, sub)
@@ -2298,7 +2317,7 @@ def _str_find(self, sub: str, start: int = 0, end: int | None = None):
)
return type(self)(result)
- def _str_join(self, sep: str):
+ def _str_join(self, sep: str) -> Self:
if pa.types.is_string(self._pa_array.type) or pa.types.is_large_string(
self._pa_array.type
):
@@ -2308,19 +2327,19 @@ def _str_join(self, sep: str):
result = self._pa_array
return type(self)(pc.binary_join(result, sep))
- def _str_partition(self, sep: str, expand: bool):
+ def _str_partition(self, sep: str, expand: bool) -> Self:
predicate = lambda val: val.partition(sep)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_rpartition(self, sep: str, expand: bool):
+ def _str_rpartition(self, sep: str, expand: bool) -> Self:
predicate = lambda val: val.rpartition(sep)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
def _str_slice(
self, start: int | None = None, stop: int | None = None, step: int | None = None
- ):
+ ) -> Self:
if start is None:
start = 0
if step is None:
@@ -2329,57 +2348,57 @@ def _str_slice(
pc.utf8_slice_codeunits(self._pa_array, start=start, stop=stop, step=step)
)
- def _str_isalnum(self):
+ def _str_isalnum(self) -> Self:
return type(self)(pc.utf8_is_alnum(self._pa_array))
- def _str_isalpha(self):
+ def _str_isalpha(self) -> Self:
return type(self)(pc.utf8_is_alpha(self._pa_array))
- def _str_isdecimal(self):
+ def _str_isdecimal(self) -> Self:
return type(self)(pc.utf8_is_decimal(self._pa_array))
- def _str_isdigit(self):
+ def _str_isdigit(self) -> Self:
return type(self)(pc.utf8_is_digit(self._pa_array))
- def _str_islower(self):
+ def _str_islower(self) -> Self:
return type(self)(pc.utf8_is_lower(self._pa_array))
- def _str_isnumeric(self):
+ def _str_isnumeric(self) -> Self:
return type(self)(pc.utf8_is_numeric(self._pa_array))
- def _str_isspace(self):
+ def _str_isspace(self) -> Self:
return type(self)(pc.utf8_is_space(self._pa_array))
- def _str_istitle(self):
+ def _str_istitle(self) -> Self:
return type(self)(pc.utf8_is_title(self._pa_array))
- def _str_isupper(self):
+ def _str_isupper(self) -> Self:
return type(self)(pc.utf8_is_upper(self._pa_array))
- def _str_len(self):
+ def _str_len(self) -> Self:
return type(self)(pc.utf8_length(self._pa_array))
- def _str_lower(self):
+ def _str_lower(self) -> Self:
return type(self)(pc.utf8_lower(self._pa_array))
- def _str_upper(self):
+ def _str_upper(self) -> Self:
return type(self)(pc.utf8_upper(self._pa_array))
- def _str_strip(self, to_strip=None):
+ def _str_strip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_trim_whitespace(self._pa_array)
else:
result = pc.utf8_trim(self._pa_array, characters=to_strip)
return type(self)(result)
- def _str_lstrip(self, to_strip=None):
+ def _str_lstrip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_ltrim_whitespace(self._pa_array)
else:
result = pc.utf8_ltrim(self._pa_array, characters=to_strip)
return type(self)(result)
- def _str_rstrip(self, to_strip=None):
+ def _str_rstrip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_rtrim_whitespace(self._pa_array)
else:
@@ -2396,12 +2415,12 @@ def _str_removeprefix(self, prefix: str):
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_casefold(self):
+ def _str_casefold(self) -> Self:
predicate = lambda val: val.casefold()
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_encode(self, encoding: str, errors: str = "strict"):
+ def _str_encode(self, encoding: str, errors: str = "strict") -> Self:
predicate = lambda val: val.encode(encoding, errors)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
@@ -2421,7 +2440,7 @@ def _str_extract(self, pat: str, flags: int = 0, expand: bool = True):
else:
return type(self)(pc.struct_field(result, [0]))
- def _str_findall(self, pat: str, flags: int = 0):
+ def _str_findall(self, pat: str, flags: int = 0) -> Self:
regex = re.compile(pat, flags=flags)
predicate = lambda val: regex.findall(val)
result = self._apply_elementwise(predicate)
@@ -2443,22 +2462,22 @@ def _str_get_dummies(self, sep: str = "|"):
result = type(self)(pa.array(list(dummies)))
return result, uniques_sorted.to_pylist()
- def _str_index(self, sub: str, start: int = 0, end: int | None = None):
+ def _str_index(self, sub: str, start: int = 0, end: int | None = None) -> Self:
predicate = lambda val: val.index(sub, start, end)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_rindex(self, sub: str, start: int = 0, end: int | None = None):
+ def _str_rindex(self, sub: str, start: int = 0, end: int | None = None) -> Self:
predicate = lambda val: val.rindex(sub, start, end)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_normalize(self, form: str):
+ def _str_normalize(self, form: str) -> Self:
predicate = lambda val: unicodedata.normalize(form, val)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_rfind(self, sub: str, start: int = 0, end=None):
+ def _str_rfind(self, sub: str, start: int = 0, end=None) -> Self:
predicate = lambda val: val.rfind(sub, start, end)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
@@ -2469,7 +2488,7 @@ def _str_split(
n: int | None = -1,
expand: bool = False,
regex: bool | None = None,
- ):
+ ) -> Self:
if n in {-1, 0}:
n = None
if pat is None:
@@ -2480,24 +2499,23 @@ def _str_split(
split_func = functools.partial(pc.split_pattern, pattern=pat)
return type(self)(split_func(self._pa_array, max_splits=n))
- def _str_rsplit(self, pat: str | None = None, n: int | None = -1):
+ def _str_rsplit(self, pat: str | None = None, n: int | None = -1) -> Self:
if n in {-1, 0}:
n = None
if pat is None:
return type(self)(
pc.utf8_split_whitespace(self._pa_array, max_splits=n, reverse=True)
)
- else:
- return type(self)(
- pc.split_pattern(self._pa_array, pat, max_splits=n, reverse=True)
- )
+ return type(self)(
+ pc.split_pattern(self._pa_array, pat, max_splits=n, reverse=True)
+ )
- def _str_translate(self, table: dict[int, str]):
+ def _str_translate(self, table: dict[int, str]) -> Self:
predicate = lambda val: val.translate(table)
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
- def _str_wrap(self, width: int, **kwargs):
+ def _str_wrap(self, width: int, **kwargs) -> Self:
kwargs["width"] = width
tw = textwrap.TextWrapper(**kwargs)
predicate = lambda val: "\n".join(tw.wrap(val))
@@ -2505,13 +2523,13 @@ def _str_wrap(self, width: int, **kwargs):
return type(self)(pa.chunked_array(result))
@property
- def _dt_days(self):
+ def _dt_days(self) -> Self:
return type(self)(
pa.array(self._to_timedeltaarray().days, from_pandas=True, type=pa.int32())
)
@property
- def _dt_hours(self):
+ def _dt_hours(self) -> Self:
return type(self)(
pa.array(
[
@@ -2523,7 +2541,7 @@ def _dt_hours(self):
)
@property
- def _dt_minutes(self):
+ def _dt_minutes(self) -> Self:
return type(self)(
pa.array(
[
@@ -2535,7 +2553,7 @@ def _dt_minutes(self):
)
@property
- def _dt_seconds(self):
+ def _dt_seconds(self) -> Self:
return type(self)(
pa.array(
self._to_timedeltaarray().seconds, from_pandas=True, type=pa.int32()
@@ -2543,7 +2561,7 @@ def _dt_seconds(self):
)
@property
- def _dt_milliseconds(self):
+ def _dt_milliseconds(self) -> Self:
return type(self)(
pa.array(
[
@@ -2555,7 +2573,7 @@ def _dt_milliseconds(self):
)
@property
- def _dt_microseconds(self):
+ def _dt_microseconds(self) -> Self:
return type(self)(
pa.array(
self._to_timedeltaarray().microseconds,
@@ -2565,25 +2583,25 @@ def _dt_microseconds(self):
)
@property
- def _dt_nanoseconds(self):
+ def _dt_nanoseconds(self) -> Self:
return type(self)(
pa.array(
self._to_timedeltaarray().nanoseconds, from_pandas=True, type=pa.int32()
)
)
- def _dt_to_pytimedelta(self):
+ def _dt_to_pytimedelta(self) -> np.ndarray:
data = self._pa_array.to_pylist()
if self._dtype.pyarrow_dtype.unit == "ns":
data = [None if ts is None else ts.to_pytimedelta() for ts in data]
return np.array(data, dtype=object)
- def _dt_total_seconds(self):
+ def _dt_total_seconds(self) -> Self:
return type(self)(
pa.array(self._to_timedeltaarray().total_seconds(), from_pandas=True)
)
- def _dt_as_unit(self, unit: str):
+ def _dt_as_unit(self, unit: str) -> Self:
if pa.types.is_date(self.dtype.pyarrow_dtype):
raise NotImplementedError("as_unit not implemented for date types")
pd_array = self._maybe_convert_datelike_array()
@@ -2591,43 +2609,43 @@ def _dt_as_unit(self, unit: str):
return type(self)(pa.array(pd_array.as_unit(unit), from_pandas=True))
@property
- def _dt_year(self):
+ def _dt_year(self) -> Self:
return type(self)(pc.year(self._pa_array))
@property
- def _dt_day(self):
+ def _dt_day(self) -> Self:
return type(self)(pc.day(self._pa_array))
@property
- def _dt_day_of_week(self):
+ def _dt_day_of_week(self) -> Self:
return type(self)(pc.day_of_week(self._pa_array))
_dt_dayofweek = _dt_day_of_week
_dt_weekday = _dt_day_of_week
@property
- def _dt_day_of_year(self):
+ def _dt_day_of_year(self) -> Self:
return type(self)(pc.day_of_year(self._pa_array))
_dt_dayofyear = _dt_day_of_year
@property
- def _dt_hour(self):
+ def _dt_hour(self) -> Self:
return type(self)(pc.hour(self._pa_array))
- def _dt_isocalendar(self):
+ def _dt_isocalendar(self) -> Self:
return type(self)(pc.iso_calendar(self._pa_array))
@property
- def _dt_is_leap_year(self):
+ def _dt_is_leap_year(self) -> Self:
return type(self)(pc.is_leap_year(self._pa_array))
@property
- def _dt_is_month_start(self):
+ def _dt_is_month_start(self) -> Self:
return type(self)(pc.equal(pc.day(self._pa_array), 1))
@property
- def _dt_is_month_end(self):
+ def _dt_is_month_end(self) -> Self:
result = pc.equal(
pc.days_between(
pc.floor_temporal(self._pa_array, unit="day"),
@@ -2638,7 +2656,7 @@ def _dt_is_month_end(self):
return type(self)(result)
@property
- def _dt_is_year_start(self):
+ def _dt_is_year_start(self) -> Self:
return type(self)(
pc.and_(
pc.equal(pc.month(self._pa_array), 1),
@@ -2647,7 +2665,7 @@ def _dt_is_year_start(self):
)
@property
- def _dt_is_year_end(self):
+ def _dt_is_year_end(self) -> Self:
return type(self)(
pc.and_(
pc.equal(pc.month(self._pa_array), 12),
@@ -2656,7 +2674,7 @@ def _dt_is_year_end(self):
)
@property
- def _dt_is_quarter_start(self):
+ def _dt_is_quarter_start(self) -> Self:
result = pc.equal(
pc.floor_temporal(self._pa_array, unit="quarter"),
pc.floor_temporal(self._pa_array, unit="day"),
@@ -2664,7 +2682,7 @@ def _dt_is_quarter_start(self):
return type(self)(result)
@property
- def _dt_is_quarter_end(self):
+ def _dt_is_quarter_end(self) -> Self:
result = pc.equal(
pc.days_between(
pc.floor_temporal(self._pa_array, unit="day"),
@@ -2675,7 +2693,7 @@ def _dt_is_quarter_end(self):
return type(self)(result)
@property
- def _dt_days_in_month(self):
+ def _dt_days_in_month(self) -> Self:
result = pc.days_between(
pc.floor_temporal(self._pa_array, unit="month"),
pc.ceil_temporal(self._pa_array, unit="month"),
@@ -2685,35 +2703,35 @@ def _dt_days_in_month(self):
_dt_daysinmonth = _dt_days_in_month
@property
- def _dt_microsecond(self):
+ def _dt_microsecond(self) -> Self:
return type(self)(pc.microsecond(self._pa_array))
@property
- def _dt_minute(self):
+ def _dt_minute(self) -> Self:
return type(self)(pc.minute(self._pa_array))
@property
- def _dt_month(self):
+ def _dt_month(self) -> Self:
return type(self)(pc.month(self._pa_array))
@property
- def _dt_nanosecond(self):
+ def _dt_nanosecond(self) -> Self:
return type(self)(pc.nanosecond(self._pa_array))
@property
- def _dt_quarter(self):
+ def _dt_quarter(self) -> Self:
return type(self)(pc.quarter(self._pa_array))
@property
- def _dt_second(self):
+ def _dt_second(self) -> Self:
return type(self)(pc.second(self._pa_array))
@property
- def _dt_date(self):
+ def _dt_date(self) -> Self:
return type(self)(self._pa_array.cast(pa.date32()))
@property
- def _dt_time(self):
+ def _dt_time(self) -> Self:
unit = (
self.dtype.pyarrow_dtype.unit
if self.dtype.pyarrow_dtype.unit in {"us", "ns"}
@@ -2729,10 +2747,10 @@ def _dt_tz(self):
def _dt_unit(self):
return self.dtype.pyarrow_dtype.unit
- def _dt_normalize(self):
+ def _dt_normalize(self) -> Self:
return type(self)(pc.floor_temporal(self._pa_array, 1, "day"))
- def _dt_strftime(self, format: str):
+ def _dt_strftime(self, format: str) -> Self:
return type(self)(pc.strftime(self._pa_array, format=format))
def _round_temporally(
@@ -2741,7 +2759,7 @@ def _round_temporally(
freq,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
- ):
+ ) -> Self:
if ambiguous != "raise":
raise NotImplementedError("ambiguous is not supported.")
if nonexistent != "raise":
@@ -2777,7 +2795,7 @@ def _dt_ceil(
freq,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
- ):
+ ) -> Self:
return self._round_temporally("ceil", freq, ambiguous, nonexistent)
def _dt_floor(
@@ -2785,7 +2803,7 @@ def _dt_floor(
freq,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
- ):
+ ) -> Self:
return self._round_temporally("floor", freq, ambiguous, nonexistent)
def _dt_round(
@@ -2793,20 +2811,20 @@ def _dt_round(
freq,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
- ):
+ ) -> Self:
return self._round_temporally("round", freq, ambiguous, nonexistent)
- def _dt_day_name(self, locale: str | None = None):
+ def _dt_day_name(self, locale: str | None = None) -> Self:
if locale is None:
locale = "C"
return type(self)(pc.strftime(self._pa_array, format="%A", locale=locale))
- def _dt_month_name(self, locale: str | None = None):
+ def _dt_month_name(self, locale: str | None = None) -> Self:
if locale is None:
locale = "C"
return type(self)(pc.strftime(self._pa_array, format="%B", locale=locale))
- def _dt_to_pydatetime(self):
+ def _dt_to_pydatetime(self) -> np.ndarray:
if pa.types.is_date(self.dtype.pyarrow_dtype):
raise ValueError(
f"to_pydatetime cannot be called with {self.dtype.pyarrow_dtype} type. "
@@ -2822,7 +2840,7 @@ def _dt_tz_localize(
tz,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
- ):
+ ) -> Self:
if ambiguous != "raise":
raise NotImplementedError(f"{ambiguous=} is not supported")
nonexistent_pa = {
@@ -2842,7 +2860,7 @@ def _dt_tz_localize(
)
return type(self)(result)
- def _dt_tz_convert(self, tz):
+ def _dt_tz_convert(self, tz) -> Self:
if self.dtype.pyarrow_dtype.tz is None:
raise TypeError(
"Cannot convert tz-naive timestamps, use tz_localize to localize"
diff --git a/pandas/core/arrays/arrow/extension_types.py b/pandas/core/arrays/arrow/extension_types.py
index d52b60df47adc..2fa5f7a882cc7 100644
--- a/pandas/core/arrays/arrow/extension_types.py
+++ b/pandas/core/arrays/arrow/extension_types.py
@@ -145,7 +145,7 @@ def patch_pyarrow() -> None:
return
class ForbiddenExtensionType(pyarrow.ExtensionType):
- def __arrow_ext_serialize__(self):
+ def __arrow_ext_serialize__(self) -> bytes:
return b""
@classmethod
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 59c6d911cfaef..e530b28cba88a 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -81,6 +81,7 @@
Sequence,
)
+ from pandas._libs.missing import NAType
from pandas._typing import (
ArrayLike,
AstypeArg,
@@ -266,7 +267,9 @@ class ExtensionArray:
# ------------------------------------------------------------------------
@classmethod
- def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+ def _from_sequence(
+ cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
+ ) -> Self:
"""
Construct a new ExtensionArray from a sequence of scalars.
@@ -329,7 +332,7 @@ def _from_scalars(cls, scalars, *, dtype: DtypeObj) -> Self:
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: Dtype | None = None, copy: bool = False
- ):
+ ) -> Self:
"""
Construct a new ExtensionArray from a sequence of strings.
@@ -2385,10 +2388,26 @@ def _groupby_op(
class ExtensionArraySupportsAnyAll(ExtensionArray):
- def any(self, *, skipna: bool = True) -> bool:
+ @overload
+ def any(self, *, skipna: Literal[True] = ...) -> bool:
+ ...
+
+ @overload
+ def any(self, *, skipna: bool) -> bool | NAType:
+ ...
+
+ def any(self, *, skipna: bool = True) -> bool | NAType:
raise AbstractMethodError(self)
- def all(self, *, skipna: bool = True) -> bool:
+ @overload
+ def all(self, *, skipna: Literal[True] = ...) -> bool:
+ ...
+
+ @overload
+ def all(self, *, skipna: bool) -> bool | NAType:
+ ...
+
+ def all(self, *, skipna: bool = True) -> bool | NAType:
raise AbstractMethodError(self)
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 8a88227ad54a3..58809ba54ed56 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -597,7 +597,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
return result
- def to_list(self):
+ def to_list(self) -> list:
"""
Alias for tolist.
"""
@@ -1017,7 +1017,9 @@ def as_unordered(self) -> Self:
"""
return self.set_ordered(False)
- def set_categories(self, new_categories, ordered=None, rename: bool = False):
+ def set_categories(
+ self, new_categories, ordered=None, rename: bool = False
+ ) -> Self:
"""
Set the categories to the specified new categories.
@@ -1870,7 +1872,7 @@ def check_for_ordered(self, op) -> None:
def argsort(
self, *, ascending: bool = True, kind: SortKind = "quicksort", **kwargs
- ):
+ ) -> npt.NDArray[np.intp]:
"""
Return the indices that would sort the Categorical.
@@ -2618,7 +2620,15 @@ def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]:
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values)
- def _replace(self, *, to_replace, value, inplace: bool = False):
+ @overload
+ def _replace(self, *, to_replace, value, inplace: Literal[False] = ...) -> Self:
+ ...
+
+ @overload
+ def _replace(self, *, to_replace, value, inplace: Literal[True]) -> None:
+ ...
+
+ def _replace(self, *, to_replace, value, inplace: bool = False) -> Self | None:
from pandas import Index
orig_dtype = self.dtype
@@ -2666,6 +2676,7 @@ def _replace(self, *, to_replace, value, inplace: bool = False):
)
if not inplace:
return cat
+ return None
# ------------------------------------------------------------------------
# String methods interface
@@ -2901,8 +2912,8 @@ def _delegate_property_get(self, name: str):
# error: Signature of "_delegate_property_set" incompatible with supertype
# "PandasDelegate"
- def _delegate_property_set(self, name: str, new_values): # type: ignore[override]
- return setattr(self._parent, name, new_values)
+ def _delegate_property_set(self, name: str, new_values) -> None: # type: ignore[override]
+ setattr(self._parent, name, new_values)
@property
def codes(self) -> Series:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 6ca74c4c05bc6..4668db8d75cd7 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -344,7 +344,7 @@ def _format_native_types(
"""
raise AbstractMethodError(self)
- def _formatter(self, boxed: bool = False):
+ def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
# TODO: Remove Datetime & DatetimeTZ formatters.
return "'{}'".format
@@ -808,9 +808,8 @@ def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]:
if self.dtype.kind in "mM":
self = cast("DatetimeArray | TimedeltaArray", self)
- # error: Item "ExtensionArray" of "ExtensionArray | ndarray[Any, Any]"
- # has no attribute "as_unit"
- values = values.as_unit(self.unit) # type: ignore[union-attr]
+ # error: "DatetimeLikeArrayMixin" has no attribute "as_unit"
+ values = values.as_unit(self.unit) # type: ignore[attr-defined]
try:
# error: Argument 1 to "_check_compatible_with" of "DatetimeLikeArrayMixin"
@@ -1209,7 +1208,7 @@ def _add_timedeltalike_scalar(self, other):
self, other = self._ensure_matching_resos(other)
return self._add_timedeltalike(other)
- def _add_timedelta_arraylike(self, other: TimedeltaArray):
+ def _add_timedelta_arraylike(self, other: TimedeltaArray) -> Self:
"""
Add a delta of a TimedeltaIndex
@@ -1222,30 +1221,26 @@ def _add_timedelta_arraylike(self, other: TimedeltaArray):
if len(self) != len(other):
raise ValueError("cannot add indices of unequal length")
- self = cast("DatetimeArray | TimedeltaArray", self)
-
- self, other = self._ensure_matching_resos(other)
+ self, other = cast(
+ "DatetimeArray | TimedeltaArray", self
+ )._ensure_matching_resos(other)
return self._add_timedeltalike(other)
@final
- def _add_timedeltalike(self, other: Timedelta | TimedeltaArray):
- self = cast("DatetimeArray | TimedeltaArray", self)
-
+ def _add_timedeltalike(self, other: Timedelta | TimedeltaArray) -> Self:
other_i8, o_mask = self._get_i8_values_and_mask(other)
new_values = add_overflowsafe(self.asi8, np.asarray(other_i8, dtype="i8"))
res_values = new_values.view(self._ndarray.dtype)
new_freq = self._get_arithmetic_result_freq(other)
- # error: Argument "dtype" to "_simple_new" of "DatetimeArray" has
- # incompatible type "Union[dtype[datetime64], DatetimeTZDtype,
- # dtype[timedelta64]]"; expected "Union[dtype[datetime64], DatetimeTZDtype]"
+ # error: Unexpected keyword argument "freq" for "_simple_new" of "NDArrayBacked"
return type(self)._simple_new(
- res_values, dtype=self.dtype, freq=new_freq # type: ignore[arg-type]
+ res_values, dtype=self.dtype, freq=new_freq # type: ignore[call-arg]
)
@final
- def _add_nat(self):
+ def _add_nat(self) -> Self:
"""
Add pd.NaT to self
"""
@@ -1253,22 +1248,19 @@ def _add_nat(self):
raise TypeError(
f"Cannot add {type(self).__name__} and {type(NaT).__name__}"
)
- self = cast("TimedeltaArray | DatetimeArray", self)
# GH#19124 pd.NaT is treated like a timedelta for both timedelta
# and datetime dtypes
result = np.empty(self.shape, dtype=np.int64)
result.fill(iNaT)
result = result.view(self._ndarray.dtype) # preserve reso
- # error: Argument "dtype" to "_simple_new" of "DatetimeArray" has
- # incompatible type "Union[dtype[timedelta64], dtype[datetime64],
- # DatetimeTZDtype]"; expected "Union[dtype[datetime64], DatetimeTZDtype]"
+ # error: Unexpected keyword argument "freq" for "_simple_new" of "NDArrayBacked"
return type(self)._simple_new(
- result, dtype=self.dtype, freq=None # type: ignore[arg-type]
+ result, dtype=self.dtype, freq=None # type: ignore[call-arg]
)
@final
- def _sub_nat(self):
+ def _sub_nat(self) -> np.ndarray:
"""
Subtract pd.NaT from self
"""
@@ -1313,7 +1305,7 @@ def _sub_periodlike(self, other: Period | PeriodArray) -> npt.NDArray[np.object_
return new_data
@final
- def _addsub_object_array(self, other: npt.NDArray[np.object_], op):
+ def _addsub_object_array(self, other: npt.NDArray[np.object_], op) -> np.ndarray:
"""
Add or subtract array-like of DateOffset objects
@@ -1364,7 +1356,7 @@ def __add__(self, other):
# scalar others
if other is NaT:
- result = self._add_nat()
+ result: np.ndarray | DatetimeLikeArrayMixin = self._add_nat()
elif isinstance(other, (Tick, timedelta, np.timedelta64)):
result = self._add_timedeltalike_scalar(other)
elif isinstance(other, BaseOffset):
@@ -1424,7 +1416,7 @@ def __sub__(self, other):
# scalar others
if other is NaT:
- result = self._sub_nat()
+ result: np.ndarray | DatetimeLikeArrayMixin = self._sub_nat()
elif isinstance(other, (Tick, timedelta, np.timedelta64)):
result = self._add_timedeltalike_scalar(-other)
elif isinstance(other, BaseOffset):
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 6b7ddc4a72957..a4d01dd6667f6 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -7,6 +7,7 @@
)
from typing import (
TYPE_CHECKING,
+ TypeVar,
cast,
overload,
)
@@ -73,7 +74,10 @@
)
if TYPE_CHECKING:
- from collections.abc import Iterator
+ from collections.abc import (
+ Generator,
+ Iterator,
+ )
from pandas._typing import (
ArrayLike,
@@ -86,9 +90,15 @@
npt,
)
- from pandas import DataFrame
+ from pandas import (
+ DataFrame,
+ Timedelta,
+ )
from pandas.core.arrays import PeriodArray
+ _TimestampNoneT1 = TypeVar("_TimestampNoneT1", Timestamp, None)
+ _TimestampNoneT2 = TypeVar("_TimestampNoneT2", Timestamp, None)
+
_ITER_CHUNKSIZE = 10_000
@@ -326,7 +336,7 @@ def _simple_new( # type: ignore[override]
return result
@classmethod
- def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False):
+ def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False) -> Self:
return cls._from_sequence_not_strict(scalars, dtype=dtype, copy=copy)
@classmethod
@@ -2125,7 +2135,7 @@ def std(
ddof: int = 1,
keepdims: bool = False,
skipna: bool = True,
- ):
+ ) -> Timedelta:
"""
Return sample standard deviation over requested axis.
@@ -2191,7 +2201,7 @@ def _sequence_to_dt64(
yearfirst: bool = False,
ambiguous: TimeAmbiguous = "raise",
out_unit: str | None = None,
-):
+) -> tuple[np.ndarray, tzinfo | None]:
"""
Parameters
----------
@@ -2360,7 +2370,7 @@ def objects_to_datetime64(
errors: DateTimeErrorChoices = "raise",
allow_object: bool = False,
out_unit: str = "ns",
-):
+) -> tuple[np.ndarray, tzinfo | None]:
"""
Convert data to array of timestamps.
@@ -2665,8 +2675,8 @@ def _infer_tz_from_endpoints(
def _maybe_normalize_endpoints(
- start: Timestamp | None, end: Timestamp | None, normalize: bool
-):
+ start: _TimestampNoneT1, end: _TimestampNoneT2, normalize: bool
+) -> tuple[_TimestampNoneT1, _TimestampNoneT2]:
if normalize:
if start is not None:
start = start.normalize()
@@ -2717,7 +2727,7 @@ def _generate_range(
offset: BaseOffset,
*,
unit: str,
-):
+) -> Generator[Timestamp, None, None]:
"""
Generates a sequence of dates corresponding to the specified time
offset. Similar to dateutil.rrule except uses pandas DateOffset
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index a19b304529383..7d2d98f71b38c 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -8,6 +8,7 @@
import textwrap
from typing import (
TYPE_CHECKING,
+ Callable,
Literal,
Union,
overload,
@@ -232,7 +233,7 @@ def __new__(
dtype: Dtype | None = None,
copy: bool = False,
verify_integrity: bool = True,
- ):
+ ) -> Self:
data = extract_array(data, extract_numpy=True)
if isinstance(data, cls):
@@ -1241,7 +1242,7 @@ def value_counts(self, dropna: bool = True) -> Series:
# ---------------------------------------------------------------------
# Rendering Methods
- def _formatter(self, boxed: bool = False):
+ def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
# returning 'str' here causes us to render as e.g. "(0, 1]" instead of
# "Interval(0, 1, closed='right')"
return str
@@ -1842,9 +1843,13 @@ def _from_combined(self, combined: np.ndarray) -> IntervalArray:
dtype = self._left.dtype
if needs_i8_conversion(dtype):
assert isinstance(self._left, (DatetimeArray, TimedeltaArray))
- new_left = type(self._left)._from_sequence(nc[:, 0], dtype=dtype)
+ new_left: DatetimeArray | TimedeltaArray | np.ndarray = type(
+ self._left
+ )._from_sequence(nc[:, 0], dtype=dtype)
assert isinstance(self._right, (DatetimeArray, TimedeltaArray))
- new_right = type(self._right)._from_sequence(nc[:, 1], dtype=dtype)
+ new_right: DatetimeArray | TimedeltaArray | np.ndarray = type(
+ self._right
+ )._from_sequence(nc[:, 1], dtype=dtype)
else:
assert isinstance(dtype, np.dtype)
new_left = nc[:, 0].view(dtype)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 03c09c5b2fd18..c1bac9cfcb02f 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -98,6 +98,7 @@
NumpySorter,
NumpyValueArrayLike,
)
+ from pandas._libs.missing import NAType
from pandas.compat.numpy import function as nv
@@ -152,7 +153,7 @@ def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False) -> Self:
@classmethod
@doc(ExtensionArray._empty)
- def _empty(cls, shape: Shape, dtype: ExtensionDtype):
+ def _empty(cls, shape: Shape, dtype: ExtensionDtype) -> Self:
values = np.empty(shape, dtype=dtype.type)
values.fill(cls._internal_fill_value)
mask = np.ones(shape, dtype=bool)
@@ -499,7 +500,7 @@ def to_numpy(
return data
@doc(ExtensionArray.tolist)
- def tolist(self):
+ def tolist(self) -> list:
if self.ndim > 1:
return [x.tolist() for x in self]
dtype = None if self._hasna else self._data.dtype
@@ -1307,7 +1308,21 @@ def max(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs):
def map(self, mapper, na_action=None):
return map_array(self.to_numpy(), mapper, na_action=None)
- def any(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs):
+ @overload
+ def any(
+ self, *, skipna: Literal[True] = ..., axis: AxisInt | None = ..., **kwargs
+ ) -> np.bool_:
+ ...
+
+ @overload
+ def any(
+ self, *, skipna: bool, axis: AxisInt | None = ..., **kwargs
+ ) -> np.bool_ | NAType:
+ ...
+
+ def any(
+ self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs
+ ) -> np.bool_ | NAType:
"""
Return whether any element is truthy.
@@ -1388,7 +1403,21 @@ def any(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs):
else:
return self.dtype.na_value
- def all(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs):
+ @overload
+ def all(
+ self, *, skipna: Literal[True] = ..., axis: AxisInt | None = ..., **kwargs
+ ) -> np.bool_:
+ ...
+
+ @overload
+ def all(
+ self, *, skipna: bool, axis: AxisInt | None = ..., **kwargs
+ ) -> np.bool_ | NAType:
+ ...
+
+ def all(
+ self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs
+ ) -> np.bool_ | NAType:
"""
Return whether all elements are truthy.
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py
index 3dd7ebf564ca1..a1d81aeeecb0b 100644
--- a/pandas/core/arrays/sparse/accessor.py
+++ b/pandas/core/arrays/sparse/accessor.py
@@ -17,6 +17,11 @@
from pandas.core.arrays.sparse.array import SparseArray
if TYPE_CHECKING:
+ from scipy.sparse import (
+ coo_matrix,
+ spmatrix,
+ )
+
from pandas import (
DataFrame,
Series,
@@ -115,7 +120,9 @@ def from_coo(cls, A, dense_index: bool = False) -> Series:
return result
- def to_coo(self, row_levels=(0,), column_levels=(1,), sort_labels: bool = False):
+ def to_coo(
+ self, row_levels=(0,), column_levels=(1,), sort_labels: bool = False
+ ) -> tuple[coo_matrix, list, list]:
"""
Create a scipy.sparse.coo_matrix from a Series with MultiIndex.
@@ -326,7 +333,7 @@ def to_dense(self) -> DataFrame:
data = {k: v.array.to_dense() for k, v in self._parent.items()}
return DataFrame(data, index=self._parent.index, columns=self._parent.columns)
- def to_coo(self):
+ def to_coo(self) -> spmatrix:
"""
Return the contents of the frame as a sparse SciPy COO matrix.
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 7a3ea85dde2b4..db670e1ea4816 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -584,11 +584,13 @@ def __setitem__(self, key, value) -> None:
raise TypeError(msg)
@classmethod
- def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+ def _from_sequence(
+ cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
+ ) -> Self:
return cls(scalars, dtype=dtype)
@classmethod
- def _from_factorized(cls, values, original):
+ def _from_factorized(cls, values, original) -> Self:
return cls(values, dtype=original.dtype)
# ------------------------------------------------------------------------
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index f451ebc352733..d4da5840689de 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -257,7 +257,7 @@ class BaseStringArray(ExtensionArray):
"""
@doc(ExtensionArray.tolist)
- def tolist(self):
+ def tolist(self) -> list:
if self.ndim > 1:
return [x.tolist() for x in self]
return list(self.to_numpy())
@@ -381,7 +381,9 @@ def _validate(self) -> None:
lib.convert_nans_to_NA(self._ndarray)
@classmethod
- def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+ def _from_sequence(
+ cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
+ ) -> Self:
if dtype and not (isinstance(dtype, str) and dtype == "string"):
dtype = pandas_dtype(dtype)
assert isinstance(dtype, StringDtype) and dtype.storage == "python"
@@ -414,7 +416,7 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: Dtype | None = None, copy: bool = False
- ):
+ ) -> Self:
return cls._from_sequence(strings, dtype=dtype, copy=copy)
@classmethod
@@ -436,7 +438,7 @@ def __arrow_array__(self, type=None):
values[self.isna()] = None
return pa.array(values, type=type, from_pandas=True)
- def _values_for_factorize(self):
+ def _values_for_factorize(self) -> tuple[np.ndarray, None]:
arr = self._ndarray.copy()
mask = self.isna()
arr[mask] = None
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index d5a76811a12e6..cb07fcf1a48fa 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -59,6 +59,7 @@
AxisInt,
Dtype,
Scalar,
+ Self,
npt,
)
@@ -172,7 +173,9 @@ def __len__(self) -> int:
return len(self._pa_array)
@classmethod
- def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+ def _from_sequence(
+ cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
+ ) -> Self:
from pandas.core.arrays.masked import BaseMaskedArray
_chk_pyarrow_available()
@@ -201,7 +204,7 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal
@classmethod
def _from_sequence_of_strings(
cls, strings, dtype: Dtype | None = None, copy: bool = False
- ):
+ ) -> Self:
return cls._from_sequence(strings, dtype=dtype, copy=copy)
@property
@@ -439,7 +442,7 @@ def _str_fullmatch(
def _str_slice(
self, start: int | None = None, stop: int | None = None, step: int | None = None
- ):
+ ) -> Self:
if stop is None:
return super()._str_slice(start, stop, step)
if start is None:
@@ -490,27 +493,27 @@ def _str_len(self):
result = pc.utf8_length(self._pa_array)
return self._convert_int_dtype(result)
- def _str_lower(self):
+ def _str_lower(self) -> Self:
return type(self)(pc.utf8_lower(self._pa_array))
- def _str_upper(self):
+ def _str_upper(self) -> Self:
return type(self)(pc.utf8_upper(self._pa_array))
- def _str_strip(self, to_strip=None):
+ def _str_strip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_trim_whitespace(self._pa_array)
else:
result = pc.utf8_trim(self._pa_array, characters=to_strip)
return type(self)(result)
- def _str_lstrip(self, to_strip=None):
+ def _str_lstrip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_ltrim_whitespace(self._pa_array)
else:
result = pc.utf8_ltrim(self._pa_array, characters=to_strip)
return type(self)(result)
- def _str_rstrip(self, to_strip=None):
+ def _str_rstrip(self, to_strip=None) -> Self:
if to_strip is None:
result = pc.utf8_rtrim_whitespace(self._pa_array)
else:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index d7a177c2a19c0..9a1ec2330a326 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1541,25 +1541,24 @@ def construct_1d_arraylike_from_scalar(
if isinstance(dtype, ExtensionDtype):
cls = dtype.construct_array_type()
seq = [] if length == 0 else [value]
- subarr = cls._from_sequence(seq, dtype=dtype).repeat(length)
+ return cls._from_sequence(seq, dtype=dtype).repeat(length)
+
+ if length and dtype.kind in "iu" and isna(value):
+ # coerce if we have nan for an integer dtype
+ dtype = np.dtype("float64")
+ elif lib.is_np_dtype(dtype, "US"):
+ # we need to coerce to object dtype to avoid
+ # to allow numpy to take our string as a scalar value
+ dtype = np.dtype("object")
+ if not isna(value):
+ value = ensure_str(value)
+ elif dtype.kind in "mM":
+ value = _maybe_box_and_unbox_datetimelike(value, dtype)
- else:
- if length and dtype.kind in "iu" and isna(value):
- # coerce if we have nan for an integer dtype
- dtype = np.dtype("float64")
- elif lib.is_np_dtype(dtype, "US"):
- # we need to coerce to object dtype to avoid
- # to allow numpy to take our string as a scalar value
- dtype = np.dtype("object")
- if not isna(value):
- value = ensure_str(value)
- elif dtype.kind in "mM":
- value = _maybe_box_and_unbox_datetimelike(value, dtype)
-
- subarr = np.empty(length, dtype=dtype)
- if length:
- # GH 47391: numpy > 1.24 will raise filling np.nan into int dtypes
- subarr.fill(value)
+ subarr = np.empty(length, dtype=dtype)
+ if length:
+ # GH 47391: numpy > 1.24 will raise filling np.nan into int dtypes
+ subarr.fill(value)
return subarr
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index e253f82256a5f..ee62441ab8f55 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -661,7 +661,9 @@ def fast_xs(self, loc: int) -> SingleArrayManager:
values = [arr[loc] for arr in self.arrays]
if isinstance(dtype, ExtensionDtype):
- result = dtype.construct_array_type()._from_sequence(values, dtype=dtype)
+ result: np.ndarray | ExtensionArray = (
+ dtype.construct_array_type()._from_sequence(values, dtype=dtype)
+ )
# for datetime64/timedelta64, the np.ndarray constructor cannot handle pd.NaT
elif is_datetime64_ns_dtype(dtype):
result = DatetimeArray._from_sequence(values, dtype=dtype)._ndarray
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 5f38720135efa..d08dee3663395 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -971,7 +971,9 @@ def fast_xs(self, loc: int) -> SingleBlockManager:
if len(self.blocks) == 1:
# TODO: this could be wrong if blk.mgr_locs is not slice(None)-like;
# is this ruled out in the general case?
- result = self.blocks[0].iget((slice(None), loc))
+ result: np.ndarray | ExtensionArray = self.blocks[0].iget(
+ (slice(None), loc)
+ )
# in the case of a single block, the new block is a view
bp = BlockPlacement(slice(0, len(result)))
block = new_block(
@@ -2368,9 +2370,9 @@ def make_na_array(dtype: DtypeObj, shape: Shape, fill_value) -> ArrayLike:
else:
# NB: we should never get here with dtype integer or bool;
# if we did, the missing_arr.fill would cast to gibberish
- missing_arr = np.empty(shape, dtype=dtype)
- missing_arr.fill(fill_value)
+ missing_arr_np = np.empty(shape, dtype=dtype)
+ missing_arr_np.fill(fill_value)
if dtype.kind in "mM":
- missing_arr = ensure_wrapped_if_datetimelike(missing_arr)
- return missing_arr
+ missing_arr_np = ensure_wrapped_if_datetimelike(missing_arr_np)
+ return missing_arr_np
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index 0029beccc40a8..29d17e7174ee9 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -205,10 +205,10 @@ def rep(x, r):
np.asarray(repeats, dtype=object),
rep,
)
- if isinstance(self, BaseStringArray):
- # Not going through map, so we have to do this here.
- result = type(self)._from_sequence(result, dtype=self.dtype)
- return result
+ if not isinstance(self, BaseStringArray):
+ return result
+ # Not going through map, so we have to do this here.
+ return type(self)._from_sequence(result, dtype=self.dtype)
def _str_match(
self, pat: str, case: bool = True, flags: int = 0, na: Scalar | None = None
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 05262c235568d..097765f5705af 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -445,7 +445,7 @@ def _convert_listlike_datetimes(
# We can take a shortcut since the datetime64 numpy array
# is in UTC
out_unit = np.datetime_data(result.dtype)[0]
- dtype = cast(DatetimeTZDtype, tz_to_dtype(tz_parsed, out_unit))
+ dtype = tz_to_dtype(tz_parsed, out_unit)
dt64_values = result.view(f"M8[{dtype.unit}]")
dta = DatetimeArray._simple_new(dt64_values, dtype=dtype)
return DatetimeIndex._simple_new(dta, name=name)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56689 | 2023-12-30T23:56:23Z | 2024-01-02T21:23:01Z | 2024-01-02T21:23:00Z | 2024-01-17T02:49:41Z |
Added validation check for integer value for series.df | diff --git a/doc/source/whatsnew/v2.3.0.rst b/doc/source/whatsnew/v2.3.0.rst
index 1f1b0c7d7195a..c0692dba32a72 100644
--- a/doc/source/whatsnew/v2.3.0.rst
+++ b/doc/source/whatsnew/v2.3.0.rst
@@ -108,6 +108,8 @@ Performance improvements
Bug fixes
~~~~~~~~~
+- Fixed bug in :meth:`Series.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)
+
Categorical
^^^^^^^^^^^
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 76fdcefd03407..128477dac562e 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -47,6 +47,7 @@
is_complex_dtype,
is_dict_like,
is_extension_array_dtype,
+ is_float,
is_float_dtype,
is_integer,
is_integer_dtype,
@@ -1361,7 +1362,12 @@ def diff(arr, n: int, axis: AxisInt = 0):
shifted
"""
- n = int(n)
+ # added a check on the integer value of period
+ # see https://github.com/pandas-dev/pandas/issues/56607
+ if not lib.is_integer(n):
+ if not (is_float(n) and n.is_integer()):
+ raise ValueError("periods must be an integer")
+ n = int(n)
na = np.nan
dtype = arr.dtype
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 1f9ac8511476e..90073e21cfd66 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -72,6 +72,7 @@
)
from pandas.core.dtypes.common import (
is_dict_like,
+ is_float,
is_integer,
is_iterator,
is_list_like,
@@ -3102,6 +3103,9 @@ def diff(self, periods: int = 1) -> Series:
--------
{examples}
"""
+ if not lib.is_integer(periods):
+ if not (is_float(periods) and periods.is_integer()):
+ raise ValueError("periods must be an integer")
result = algorithms.diff(self._values, periods)
return self._constructor(result, index=self.index, copy=False).__finalize__(
self, method="diff"
diff --git a/pandas/tests/series/methods/test_diff.py b/pandas/tests/series/methods/test_diff.py
index 18de81a927c3a..a46389087f87b 100644
--- a/pandas/tests/series/methods/test_diff.py
+++ b/pandas/tests/series/methods/test_diff.py
@@ -10,6 +10,11 @@
class TestSeriesDiff:
+ def test_diff_series_requires_integer(self):
+ series = Series(np.random.default_rng(2).standard_normal(2))
+ with pytest.raises(ValueError, match="periods must be an integer"):
+ series.diff(1.5)
+
def test_diff_np(self):
# TODO(__array_function__): could make np.diff return a Series
# matching ser.diff()
| - [1] closes #56607
- [2] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [3 ] Imported is_float from from pandas.core.dtypes.common for the check and added an if statement to raise the ValueError. | https://api.github.com/repos/pandas-dev/pandas/pulls/56688 | 2023-12-30T20:16:41Z | 2024-01-07T16:18:47Z | 2024-01-07T16:18:47Z | 2024-01-07T16:18:47Z |
Backport PR #56312 on branch 2.2.x (DOC: Add whatsnew for concat regression) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..649ad37a56b35 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -761,6 +761,7 @@ Datetimelike
- Bug in parsing datetime strings with nanosecond resolution with non-ISO8601 formats incorrectly truncating sub-microsecond components (:issue:`56051`)
- Bug in parsing datetime strings with sub-second resolution and trailing zeros incorrectly inferring second or millisecond resolution (:issue:`55737`)
- Bug in the results of :func:`to_datetime` with an floating-dtype argument with ``unit`` not matching the pointwise results of :class:`Timestamp` (:issue:`56037`)
+- Fixed regression where :func:`concat` would raise an error when concatenating ``datetime64`` columns with differing resolutions (:issue:`53641`)
Timedelta
^^^^^^^^^
| Backport PR #56312: DOC: Add whatsnew for concat regression | https://api.github.com/repos/pandas-dev/pandas/pulls/56686 | 2023-12-30T15:33:57Z | 2023-12-30T19:05:18Z | 2023-12-30T19:05:18Z | 2023-12-30T19:05:18Z |
add test for concating tzaware series with empty series. Issue: #34174 | diff --git a/pandas/tests/dtypes/test_concat.py b/pandas/tests/dtypes/test_concat.py
index 97718386dabb7..4f7ae6fa2a0a0 100644
--- a/pandas/tests/dtypes/test_concat.py
+++ b/pandas/tests/dtypes/test_concat.py
@@ -49,3 +49,20 @@ def test_concat_periodarray_2d():
with pytest.raises(ValueError, match=msg):
_concat.concat_compat([arr[:2], arr[2:]], axis=1)
+
+
+def test_concat_series_between_empty_and_tzaware_series():
+ tzaware_time = pd.Timestamp("2020-01-01T00:00:00+00:00")
+ ser1 = Series(index=[tzaware_time], data=0, dtype=float)
+ ser2 = Series(dtype=float)
+
+ result = pd.concat([ser1, ser2], axis=1)
+ expected = pd.DataFrame(
+ data=[
+ (0.0, None),
+ ],
+ index=pd.Index([tzaware_time], dtype=object),
+ columns=[0, 1],
+ dtype=float,
+ )
+ tm.assert_frame_equal(result, expected)
| - [x] closes #34174
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56685 | 2023-12-30T15:04:26Z | 2024-01-03T18:37:37Z | 2024-01-03T18:37:37Z | 2024-01-03T18:37:43Z |
Backport PR #56682 on branch 2.2.x (CLN: NEP 50 followups) | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 12e645dc9da81..dd5d090e098b0 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -92,7 +92,7 @@ jobs:
- name: "Numpy Dev"
env_file: actions-311-numpydev.yaml
pattern: "not slow and not network and not single_cpu"
- test_args: "-W error::FutureWarning"
+ test_args: "-W error::DeprecationWarning -W error::FutureWarning"
- name: "Pyarrow Nightly"
env_file: actions-311-pyarrownightly.yaml
pattern: "not slow and not network and not single_cpu"
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 4b62ecc79e4ef..45f114322015b 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-311-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml
index 95c0319d6f5b8..d6bf9ec7843de 100644
--- a/ci/deps/actions-311-downstream_compat.yaml
+++ b/ci/deps/actions-311-downstream_compat.yaml
@@ -21,7 +21,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-311-pyarrownightly.yaml b/ci/deps/actions-311-pyarrownightly.yaml
index 5455b9b84b034..d84063ac2a9ba 100644
--- a/ci/deps/actions-311-pyarrownightly.yaml
+++ b/ci/deps/actions-311-pyarrownightly.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
- pip
diff --git a/ci/deps/actions-311-sanitizers.yaml b/ci/deps/actions-311-sanitizers.yaml
index dcd381066b0ea..f5f04c90bffad 100644
--- a/ci/deps/actions-311-sanitizers.yaml
+++ b/ci/deps/actions-311-sanitizers.yaml
@@ -22,7 +22,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# pandas dependencies
diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml
index 52074ae00ea18..d14686696e669 100644
--- a/ci/deps/actions-311.yaml
+++ b/ci/deps/actions-311.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-312.yaml b/ci/deps/actions-312.yaml
index 4c51e9e6029e3..86aaf24b4e15c 100644
--- a/ci/deps/actions-312.yaml
+++ b/ci/deps/actions-312.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-39-minimum_versions.yaml b/ci/deps/actions-39-minimum_versions.yaml
index fd71315d2e7ac..7067048c4434d 100644
--- a/ci/deps/actions-39-minimum_versions.yaml
+++ b/ci/deps/actions-39-minimum_versions.yaml
@@ -22,7 +22,7 @@ dependencies:
# required dependencies
- python-dateutil=2.8.2
- - numpy=1.22.4, <2
+ - numpy=1.22.4
- pytz=2020.1
# optional dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index cbe8f77c15730..31ee74174cd46 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-pypy-39.yaml b/ci/deps/actions-pypy-39.yaml
index 5a5a01f7aec72..d9c8dd81b7c33 100644
--- a/ci/deps/actions-pypy-39.yaml
+++ b/ci/deps/actions-pypy-39.yaml
@@ -20,7 +20,7 @@ dependencies:
- hypothesis>=6.46.1
# required
- - numpy<2
+ - numpy
- python-dateutil
- pytz
- pip:
diff --git a/ci/deps/circle-310-arm64.yaml b/ci/deps/circle-310-arm64.yaml
index 8e106445cd4e0..a19ffd485262d 100644
--- a/ci/deps/circle-310-arm64.yaml
+++ b/ci/deps/circle-310-arm64.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 7a088bf84c48e..259e83a5936d7 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1332,7 +1332,7 @@ def find_result_type(left_dtype: DtypeObj, right: Any) -> DtypeObj:
right = left_dtype
elif (
not np.issubdtype(left_dtype, np.unsignedinteger)
- and 0 < right <= 2 ** (8 * right_dtype.itemsize - 1) - 1
+ and 0 < right <= np.iinfo(right_dtype).max
):
# If left dtype isn't unsigned, check if it fits in the signed dtype
right = np.dtype(f"i{right_dtype.itemsize}")
| Backport PR #56682: CLN: NEP 50 followups | https://api.github.com/repos/pandas-dev/pandas/pulls/56684 | 2023-12-29T22:59:27Z | 2023-12-29T23:47:36Z | 2023-12-29T23:47:36Z | 2023-12-29T23:47:36Z |
Backport PR #56666 on branch 2.2.x (STY: Use ruff instead of pygrep check for future annotation import) | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7f3fc95ce00cc..4b02ad7cf886f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -358,18 +358,6 @@ repos:
files: ^pandas/
exclude: ^(pandas/_libs/|pandas/tests/|pandas/errors/__init__.py$|pandas/_version.py)
types: [python]
- - id: future-annotations
- name: import annotations from __future__
- entry: 'from __future__ import annotations'
- language: pygrep
- args: [--negate]
- files: ^pandas/
- types: [python]
- exclude: |
- (?x)
- /(__init__\.py)|(api\.py)|(_version\.py)|(testing\.py)|(conftest\.py)$
- |/tests/
- |/_testing/
- id: check-test-naming
name: check that test names start with 'test'
entry: python -m scripts.check_test_naming
diff --git a/pyproject.toml b/pyproject.toml
index 5e65edf81f9c7..8724a25909543 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -259,6 +259,8 @@ select = [
"FLY",
# flake8-logging-format
"G",
+ # flake8-future-annotations
+ "FA",
]
ignore = [
| Backport PR #56666: STY: Use ruff instead of pygrep check for future annotation import | https://api.github.com/repos/pandas-dev/pandas/pulls/56683 | 2023-12-29T21:54:07Z | 2023-12-29T22:58:59Z | 2023-12-29T22:58:59Z | 2023-12-29T22:58:59Z |
CLN: NEP 50 followups | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 6ca4d19196874..293cf3a6a9bac 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -92,7 +92,7 @@ jobs:
- name: "Numpy Dev"
env_file: actions-311-numpydev.yaml
pattern: "not slow and not network and not single_cpu"
- test_args: "-W error::FutureWarning"
+ test_args: "-W error::DeprecationWarning -W error::FutureWarning"
- name: "Pyarrow Nightly"
env_file: actions-311-pyarrownightly.yaml
pattern: "not slow and not network and not single_cpu"
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 4b62ecc79e4ef..45f114322015b 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-311-downstream_compat.yaml b/ci/deps/actions-311-downstream_compat.yaml
index 95c0319d6f5b8..d6bf9ec7843de 100644
--- a/ci/deps/actions-311-downstream_compat.yaml
+++ b/ci/deps/actions-311-downstream_compat.yaml
@@ -21,7 +21,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-311-pyarrownightly.yaml b/ci/deps/actions-311-pyarrownightly.yaml
index 5455b9b84b034..d84063ac2a9ba 100644
--- a/ci/deps/actions-311-pyarrownightly.yaml
+++ b/ci/deps/actions-311-pyarrownightly.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
- pip
diff --git a/ci/deps/actions-311-sanitizers.yaml b/ci/deps/actions-311-sanitizers.yaml
index dcd381066b0ea..f5f04c90bffad 100644
--- a/ci/deps/actions-311-sanitizers.yaml
+++ b/ci/deps/actions-311-sanitizers.yaml
@@ -22,7 +22,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# pandas dependencies
diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml
index 52074ae00ea18..d14686696e669 100644
--- a/ci/deps/actions-311.yaml
+++ b/ci/deps/actions-311.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-312.yaml b/ci/deps/actions-312.yaml
index 4c51e9e6029e3..86aaf24b4e15c 100644
--- a/ci/deps/actions-312.yaml
+++ b/ci/deps/actions-312.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-39-minimum_versions.yaml b/ci/deps/actions-39-minimum_versions.yaml
index fd71315d2e7ac..7067048c4434d 100644
--- a/ci/deps/actions-39-minimum_versions.yaml
+++ b/ci/deps/actions-39-minimum_versions.yaml
@@ -22,7 +22,7 @@ dependencies:
# required dependencies
- python-dateutil=2.8.2
- - numpy=1.22.4, <2
+ - numpy=1.22.4
- pytz=2020.1
# optional dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index cbe8f77c15730..31ee74174cd46 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-pypy-39.yaml b/ci/deps/actions-pypy-39.yaml
index 5a5a01f7aec72..d9c8dd81b7c33 100644
--- a/ci/deps/actions-pypy-39.yaml
+++ b/ci/deps/actions-pypy-39.yaml
@@ -20,7 +20,7 @@ dependencies:
- hypothesis>=6.46.1
# required
- - numpy<2
+ - numpy
- python-dateutil
- pytz
- pip:
diff --git a/ci/deps/circle-310-arm64.yaml b/ci/deps/circle-310-arm64.yaml
index 8e106445cd4e0..a19ffd485262d 100644
--- a/ci/deps/circle-310-arm64.yaml
+++ b/ci/deps/circle-310-arm64.yaml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<2
+ - numpy
- pytz
# optional dependencies
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 72c33e95f68a0..d7a177c2a19c0 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1332,7 +1332,7 @@ def find_result_type(left_dtype: DtypeObj, right: Any) -> DtypeObj:
right = left_dtype
elif (
not np.issubdtype(left_dtype, np.unsignedinteger)
- and 0 < right <= 2 ** (8 * right_dtype.itemsize - 1) - 1
+ and 0 < right <= np.iinfo(right_dtype).max
):
# If left dtype isn't unsigned, check if it fits in the signed dtype
right = np.dtype(f"i{right_dtype.itemsize}")
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56682 | 2023-12-29T18:52:52Z | 2023-12-29T22:59:21Z | 2023-12-29T22:59:20Z | 2024-03-16T17:12:32Z |
DEPR: utcnow, utcfromtimestamp | diff --git a/doc/source/whatsnew/v2.3.0.rst b/doc/source/whatsnew/v2.3.0.rst
index 1f1b0c7d7195a..bba1ab68d9d05 100644
--- a/doc/source/whatsnew/v2.3.0.rst
+++ b/doc/source/whatsnew/v2.3.0.rst
@@ -92,7 +92,8 @@ Other API changes
Deprecations
~~~~~~~~~~~~
--
+- Deprecated :meth:`Timestamp.utcfromtimestamp`, use ``Timestamp.fromtimestamp(ts, "UTC")`` instead (:issue:`56680`)
+- Deprecated :meth:`Timestamp.utcnow`, use ``Timestamp.now("UTC")`` instead (:issue:`56680`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx
index ee72b1311051e..c09835c9661f3 100644
--- a/pandas/_libs/tslibs/strptime.pyx
+++ b/pandas/_libs/tslibs/strptime.pyx
@@ -132,7 +132,7 @@ cdef bint parse_today_now(
if infer_reso:
creso = NPY_DATETIMEUNIT.NPY_FR_us
if utc:
- ts = <_Timestamp>Timestamp.utcnow()
+ ts = <_Timestamp>Timestamp.now(timezone.utc)
iresult[0] = ts._as_creso(creso)._value
else:
# GH#18705 make sure to_datetime("now") matches Timestamp("now")
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 568539b53aee0..1dae2403706e8 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -1418,6 +1418,14 @@ class Timestamp(_Timestamp):
>>> pd.Timestamp.utcnow() # doctest: +SKIP
Timestamp('2020-11-16 22:50:18.092888+0000', tz='UTC')
"""
+ warnings.warn(
+ # The stdlib datetime.utcnow is deprecated, so we deprecate to match.
+ # GH#56680
+ "Timestamp.utcnow is deprecated and will be removed in a future "
+ "version. Use Timestamp.now('UTC') instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return cls.now(UTC)
@classmethod
@@ -1438,6 +1446,14 @@ class Timestamp(_Timestamp):
Timestamp('2020-03-14 15:32:52+0000', tz='UTC')
"""
# GH#22451
+ warnings.warn(
+ # The stdlib datetime.utcfromtimestamp is deprecated, so we deprecate
+ # to match. GH#56680
+ "Timestamp.utcfromtimestamp is deprecated and will be removed in a "
+ "future version. Use Timestamp.fromtimestamp(ts, 'UTC') instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return cls.fromtimestamp(ts, tz="UTC")
@classmethod
diff --git a/pandas/tests/groupby/methods/test_groupby_shift_diff.py b/pandas/tests/groupby/methods/test_groupby_shift_diff.py
index 94e672d4892fe..41e0ee93a5941 100644
--- a/pandas/tests/groupby/methods/test_groupby_shift_diff.py
+++ b/pandas/tests/groupby/methods/test_groupby_shift_diff.py
@@ -63,7 +63,7 @@ def test_group_shift_with_fill_value():
def test_group_shift_lose_timezone():
# GH 30134
- now_dt = Timestamp.utcnow().as_unit("ns")
+ now_dt = Timestamp.now("UTC").as_unit("ns")
df = DataFrame({"a": [1, 1], "date": now_dt})
result = df.groupby("a").shift(0).iloc[0]
expected = Series({"date": now_dt}, name=result.name)
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index 3975f3c46aaa1..f92e9145a2205 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -28,6 +28,7 @@
Timedelta,
Timestamp,
)
+import pandas._testing as tm
class TestTimestampConstructorUnitKeyword:
@@ -329,6 +330,18 @@ def test_constructor_positional_keyword_mixed_with_tzinfo(self, kwd, request):
class TestTimestampClassMethodConstructors:
# Timestamp constructors other than __new__
+ def test_utcnow_deprecated(self):
+ # GH#56680
+ msg = "Timestamp.utcnow is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ Timestamp.utcnow()
+
+ def test_utcfromtimestamp_deprecated(self):
+ # GH#56680
+ msg = "Timestamp.utcfromtimestamp is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ Timestamp.utcfromtimestamp(43)
+
def test_constructor_strptime(self):
# GH#25016
# Test support for Timestamp.strptime
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index 05e1c93e1a676..e0734b314a0bd 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -269,7 +269,9 @@ def test_disallow_setting_tz(self, tz):
ts.tz = tz
def test_default_to_stdlib_utc(self):
- assert Timestamp.utcnow().tz is timezone.utc
+ msg = "Timestamp.utcnow is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert Timestamp.utcnow().tz is timezone.utc
assert Timestamp.now("UTC").tz is timezone.utc
assert Timestamp("2016-01-01", tz="UTC").tz is timezone.utc
@@ -312,11 +314,15 @@ def compare(x, y):
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now("UTC"), datetime.now(pytz.timezone("UTC")))
compare(Timestamp.now("UTC"), datetime.now(tzutc()))
- compare(Timestamp.utcnow(), datetime.now(timezone.utc))
+ msg = "Timestamp.utcnow is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ compare(Timestamp.utcnow(), datetime.now(timezone.utc))
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
- ts_utc = Timestamp.utcfromtimestamp(current_time)
+ msg = "Timestamp.utcfromtimestamp is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ ts_utc = Timestamp.utcfromtimestamp(current_time)
assert ts_utc.timestamp() == current_time
compare(
Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index cb94427ae8961..e4e87a4b9c95e 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -1073,6 +1073,7 @@ def test_to_datetime_today(self, tz):
def test_to_datetime_today_now_unicode_bytes(self, arg):
to_datetime([arg])
+ @pytest.mark.filterwarnings("ignore:Timestamp.utcnow is deprecated:FutureWarning")
@pytest.mark.parametrize(
"format, expected_ds",
[
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
The stdlib has deprecated these, let's do it too! | https://api.github.com/repos/pandas-dev/pandas/pulls/56680 | 2023-12-29T17:47:56Z | 2024-01-08T21:23:54Z | 2024-01-08T21:23:54Z | 2024-01-11T00:05:19Z |
Fix integral truediv and floordiv for pyarrow types with large divisor and avoid floating points for floordiv | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..75971f4ca109e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -776,6 +776,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` and :meth:`Series.__truediv__` for :class:`ArrowDtype` with integral dtypes raising for large divisors (:issue:`56706`)
- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..3633e3f5d75d8 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -109,30 +109,50 @@
def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
- ) -> pa.ChunkedArray:
+ ) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
+ # GH: 56645.
# https://github.com/apache/arrow/issues/35563
- # Arrow does not allow safe casting large integral values to float64.
- # Intentionally not using arrow_array.cast because it could be a scalar
- # value in reflected case, and safe=False only added to
- # scalar cast in pyarrow 13.
- return pc.cast(arrow_array, pa.float64(), safe=False)
- return arrow_array
+ return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast(
+ pa_object, pa.float64(), safe=False
+ )
+
+ return arrow_array, pa_object
def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
right: pa.ChunkedArray | pa.Array | pa.Scalar,
) -> pa.ChunkedArray:
- # Ensure int // int -> int mirroring Python/Numpy behavior
- # as pc.floor(pc.divide_checked(int, int)) -> float
- converted_left = cast_for_truediv(left, right)
- result = pc.floor(pc.divide(converted_left, right))
+ # TODO: Replace with pyarrow floordiv kernel.
+ # https://github.com/apache/arrow/issues/39386
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
+ divided = pc.divide_checked(left, right)
+ if pa.types.is_signed_integer(divided.type):
+ # GH 56676
+ has_remainder = pc.not_equal(pc.multiply(divided, right), left)
+ has_one_negative_operand = pc.less(
+ pc.bit_wise_xor(left, right),
+ pa.scalar(0, type=divided.type),
+ )
+ result = pc.if_else(
+ pc.and_(
+ has_remainder,
+ has_one_negative_operand,
+ ),
+ # GH: 55561
+ pc.subtract(divided, pa.scalar(1, type=divided.type)),
+ divided,
+ )
+ else:
+ result = divided
result = result.cast(left.type)
+ else:
+ divided = pc.divide(left, right)
+ result = pc.floor(divided)
return result
ARROW_ARITHMETIC_FUNCS = {
@@ -142,8 +162,8 @@ def floordiv_compat(
"rsub": lambda x, y: pc.subtract_checked(y, x),
"mul": pc.multiply_checked,
"rmul": lambda x, y: pc.multiply_checked(y, x),
- "truediv": lambda x, y: pc.divide(cast_for_truediv(x, y), y),
- "rtruediv": lambda x, y: pc.divide(y, cast_for_truediv(x, y)),
+ "truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)),
+ "rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..7ce2e841a76f8 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3239,13 +3239,82 @@ def test_arrow_floordiv():
def test_arrow_floordiv_large_values():
- # GH 55561
+ # GH 56645
a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
expected = pd.Series([1425801600000], dtype="int64[pyarrow]")
result = a // 1_000_000
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_floordiv_large_integral_result(dtype):
+ # GH 56676
+ a = pd.Series([18014398509481983], dtype=dtype)
+ result = a // 1
+ tm.assert_series_equal(result, a)
+
+
+@pytest.mark.parametrize("pa_type", tm.SIGNED_INT_PYARROW_DTYPES)
+def test_arrow_floordiv_larger_divisor(pa_type):
+ # GH 56676
+ dtype = ArrowDtype(pa_type)
+ a = pd.Series([-23], dtype=dtype)
+ result = a // 24
+ expected = pd.Series([-1], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.SIGNED_INT_PYARROW_DTYPES)
+def test_arrow_floordiv_integral_invalid(pa_type):
+ # GH 56676
+ min_value = np.iinfo(pa_type.to_pandas_dtype()).min
+ a = pd.Series([min_value], dtype=ArrowDtype(pa_type))
+ with pytest.raises(pa.lib.ArrowInvalid, match="overflow|not in range"):
+ a // -1
+ with pytest.raises(pa.lib.ArrowInvalid, match="divide by zero"):
+ a // 0
+
+
+@pytest.mark.parametrize("dtype", tm.FLOAT_PYARROW_DTYPES_STR_REPR)
+def test_arrow_floordiv_floating_0_divisor(dtype):
+ # GH 56676
+ a = pd.Series([2], dtype=dtype)
+ result = a // 0
+ expected = pd.Series([float("inf")], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES)
+def test_arrow_integral_floordiv_large_values(pa_type):
+ # GH 56676
+ max_value = np.iinfo(pa_type.to_pandas_dtype()).max
+ dtype = ArrowDtype(pa_type)
+ a = pd.Series([max_value], dtype=dtype)
+ b = pd.Series([1], dtype=dtype)
+ result = a // b
+ tm.assert_series_equal(result, a)
+
+
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_true_division_large_divisor(dtype):
+ # GH 56706
+ a = pd.Series([0], dtype=dtype)
+ b = pd.Series([18014398509481983], dtype=dtype)
+ expected = pd.Series([0], dtype="float64[pyarrow]")
+ result = a / b
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["int64[pyarrow]", "uint64[pyarrow]"])
+def test_arrow_floor_division_large_divisor(dtype):
+ # GH 56706
+ a = pd.Series([0], dtype=dtype)
+ b = pd.Series([18014398509481983], dtype=dtype)
+ expected = pd.Series([0], dtype=dtype)
+ result = a // b
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| - [x] closes #56676(Replace xxxx with the GitHub issue number)
- [x] closes #56706(Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56677 | 2023-12-29T04:29:31Z | 2024-01-05T18:08:22Z | 2024-01-05T18:08:22Z | 2024-01-05T22:44:52Z |
TYP: more misc annotations | diff --git a/pandas/_config/config.py b/pandas/_config/config.py
index c391939d22491..73d69105541d8 100644
--- a/pandas/_config/config.py
+++ b/pandas/_config/config.py
@@ -75,6 +75,7 @@
from collections.abc import (
Generator,
Iterable,
+ Sequence,
)
@@ -853,7 +854,7 @@ def inner(x) -> None:
return inner
-def is_instance_factory(_type) -> Callable[[Any], None]:
+def is_instance_factory(_type: type | tuple[type, ...]) -> Callable[[Any], None]:
"""
Parameters
@@ -866,8 +867,7 @@ def is_instance_factory(_type) -> Callable[[Any], None]:
ValueError if x is not an instance of `_type`
"""
- if isinstance(_type, (tuple, list)):
- _type = tuple(_type)
+ if isinstance(_type, tuple):
type_repr = "|".join(map(str, _type))
else:
type_repr = f"'{_type}'"
@@ -879,7 +879,7 @@ def inner(x) -> None:
return inner
-def is_one_of_factory(legal_values) -> Callable[[Any], None]:
+def is_one_of_factory(legal_values: Sequence) -> Callable[[Any], None]:
callables = [c for c in legal_values if callable(c)]
legal_values = [c for c in legal_values if not callable(c)]
@@ -930,7 +930,7 @@ def is_nonnegative_int(value: object) -> None:
is_text = is_instance_factory((str, bytes))
-def is_callable(obj) -> bool:
+def is_callable(obj: object) -> bool:
"""
Parameters
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 2930b979bfe78..df5ec356175bf 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -759,7 +759,7 @@ def asfreq(self, freq=None, how: str = "E") -> Self:
# ------------------------------------------------------------------
# Rendering Methods
- def _formatter(self, boxed: bool = False):
+ def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
if boxed:
return str
return "'{}'".format
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 1b885a2bdcd47..58455f8cb8398 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -1080,7 +1080,7 @@ def sequence_to_td64ns(
return data, inferred_freq
-def _ints_to_td64ns(data, unit: str = "ns"):
+def _ints_to_td64ns(data, unit: str = "ns") -> tuple[np.ndarray, bool]:
"""
Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating
the integers as multiples of the given timedelta unit.
@@ -1120,7 +1120,9 @@ def _ints_to_td64ns(data, unit: str = "ns"):
return data, copy_made
-def _objects_to_td64ns(data, unit=None, errors: DateTimeErrorChoices = "raise"):
+def _objects_to_td64ns(
+ data, unit=None, errors: DateTimeErrorChoices = "raise"
+) -> np.ndarray:
"""
Convert a object-dtyped or string-dtyped array into an
timedelta64[ns]-dtyped array.
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index a8b63f97141c2..0a9d5af7cbd42 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -329,7 +329,7 @@ def is_terminal() -> bool:
"min_rows",
10,
pc_min_rows_doc,
- validator=is_instance_factory([type(None), int]),
+ validator=is_instance_factory((type(None), int)),
)
cf.register_option("max_categories", 8, pc_max_categories_doc, validator=is_int)
@@ -369,7 +369,7 @@ def is_terminal() -> bool:
cf.register_option("chop_threshold", None, pc_chop_threshold_doc)
cf.register_option("max_seq_items", 100, pc_max_seq_items)
cf.register_option(
- "width", 80, pc_width_doc, validator=is_instance_factory([type(None), int])
+ "width", 80, pc_width_doc, validator=is_instance_factory((type(None), int))
)
cf.register_option(
"memory_usage",
@@ -850,14 +850,14 @@ def register_converter_cb(key) -> None:
"format.thousands",
None,
styler_thousands,
- validator=is_instance_factory([type(None), str]),
+ validator=is_instance_factory((type(None), str)),
)
cf.register_option(
"format.na_rep",
None,
styler_na_rep,
- validator=is_instance_factory([type(None), str]),
+ validator=is_instance_factory((type(None), str)),
)
cf.register_option(
@@ -867,11 +867,15 @@ def register_converter_cb(key) -> None:
validator=is_one_of_factory([None, "html", "latex", "latex-math"]),
)
+ # error: Argument 1 to "is_instance_factory" has incompatible type "tuple[
+ # ..., <typing special form>, ...]"; expected "type | tuple[type, ...]"
cf.register_option(
"format.formatter",
None,
styler_formatter,
- validator=is_instance_factory([type(None), dict, Callable, str]),
+ validator=is_instance_factory(
+ (type(None), dict, Callable, str) # type: ignore[arg-type]
+ ),
)
cf.register_option("html.mathjax", True, styler_mathjax, validator=is_bool)
@@ -898,7 +902,7 @@ def register_converter_cb(key) -> None:
"latex.environment",
None,
styler_environment,
- validator=is_instance_factory([type(None), str]),
+ validator=is_instance_factory((type(None), str)),
)
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 4dc0d477f89e8..3e4227a8a2598 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -557,11 +557,13 @@ def _array_equivalent_float(left: np.ndarray, right: np.ndarray) -> bool:
return bool(((left == right) | (np.isnan(left) & np.isnan(right))).all())
-def _array_equivalent_datetimelike(left: np.ndarray, right: np.ndarray):
+def _array_equivalent_datetimelike(left: np.ndarray, right: np.ndarray) -> bool:
return np.array_equal(left.view("i8"), right.view("i8"))
-def _array_equivalent_object(left: np.ndarray, right: np.ndarray, strict_nan: bool):
+def _array_equivalent_object(
+ left: np.ndarray, right: np.ndarray, strict_nan: bool
+) -> bool:
left = ensure_object(left)
right = ensure_object(right)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c24ef4d6d6d42..73b5804d8c168 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -233,6 +233,7 @@
IndexLabel,
JoinValidate,
Level,
+ ListLike,
MergeHow,
MergeValidate,
MutableMappingT,
@@ -5349,11 +5350,11 @@ def reindex(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level = ...,
inplace: Literal[True],
errors: IgnoreRaise = ...,
@@ -5363,11 +5364,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level = ...,
inplace: Literal[False] = ...,
errors: IgnoreRaise = ...,
@@ -5377,11 +5378,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level = ...,
inplace: bool = ...,
errors: IgnoreRaise = ...,
@@ -5390,11 +5391,11 @@ def drop(
def drop(
self,
- labels: IndexLabel | None = None,
+ labels: IndexLabel | ListLike = None,
*,
axis: Axis = 0,
- index: IndexLabel | None = None,
- columns: IndexLabel | None = None,
+ index: IndexLabel | ListLike = None,
+ columns: IndexLabel | ListLike = None,
level: Level | None = None,
inplace: bool = False,
errors: IgnoreRaise = "raise",
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 91a150c63c5b6..9b70c24aa67c6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -65,6 +65,7 @@
IntervalClosedType,
JSONSerializable,
Level,
+ ListLike,
Manager,
NaPosition,
NDFrameT,
@@ -4709,11 +4710,11 @@ def reindex_like(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[True],
errors: IgnoreRaise = ...,
@@ -4723,11 +4724,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[False] = ...,
errors: IgnoreRaise = ...,
@@ -4737,11 +4738,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: bool_t = ...,
errors: IgnoreRaise = ...,
@@ -4750,11 +4751,11 @@ def drop(
def drop(
self,
- labels: IndexLabel | None = None,
+ labels: IndexLabel | ListLike = None,
*,
axis: Axis = 0,
- index: IndexLabel | None = None,
- columns: IndexLabel | None = None,
+ index: IndexLabel | ListLike = None,
+ columns: IndexLabel | ListLike = None,
level: Level | None = None,
inplace: bool_t = False,
errors: IgnoreRaise = "raise",
diff --git a/pandas/core/methods/selectn.py b/pandas/core/methods/selectn.py
index a2f8ca94134b8..5256c0a1c73a4 100644
--- a/pandas/core/methods/selectn.py
+++ b/pandas/core/methods/selectn.py
@@ -10,6 +10,7 @@
)
from typing import (
TYPE_CHECKING,
+ Generic,
cast,
final,
)
@@ -32,16 +33,25 @@
from pandas._typing import (
DtypeObj,
IndexLabel,
+ NDFrameT,
)
from pandas import (
DataFrame,
Series,
)
+else:
+ # Generic[...] requires a non-str, provide it with a plain TypeVar at
+ # runtime to avoid circular imports
+ from pandas._typing import T
+ NDFrameT = T
+ DataFrame = T
+ Series = T
-class SelectN:
- def __init__(self, obj, n: int, keep: str) -> None:
+
+class SelectN(Generic[NDFrameT]):
+ def __init__(self, obj: NDFrameT, n: int, keep: str) -> None:
self.obj = obj
self.n = n
self.keep = keep
@@ -49,15 +59,15 @@ def __init__(self, obj, n: int, keep: str) -> None:
if self.keep not in ("first", "last", "all"):
raise ValueError('keep must be either "first", "last" or "all"')
- def compute(self, method: str) -> DataFrame | Series:
+ def compute(self, method: str) -> NDFrameT:
raise NotImplementedError
@final
- def nlargest(self):
+ def nlargest(self) -> NDFrameT:
return self.compute("nlargest")
@final
- def nsmallest(self):
+ def nsmallest(self) -> NDFrameT:
return self.compute("nsmallest")
@final
@@ -72,7 +82,7 @@ def is_valid_dtype_n_method(dtype: DtypeObj) -> bool:
return needs_i8_conversion(dtype)
-class SelectNSeries(SelectN):
+class SelectNSeries(SelectN[Series]):
"""
Implement n largest/smallest for Series
@@ -163,7 +173,7 @@ def compute(self, method: str) -> Series:
return concat([dropped.iloc[inds], nan_index]).iloc[:findex]
-class SelectNFrame(SelectN):
+class SelectNFrame(SelectN[DataFrame]):
"""
Implement n largest/smallest for DataFrame
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index d275445983b6f..0d857f6b21517 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -960,14 +960,11 @@ def _pad_2d(
values: np.ndarray,
limit: int | None = None,
mask: npt.NDArray[np.bool_] | None = None,
-):
+) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
if values.size:
algos.pad_2d_inplace(values, mask, limit=limit)
- else:
- # for test coverage
- pass
return values, mask
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e3b401cd3c88b..487f57b7390a8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -179,6 +179,7 @@
IndexKeyFunc,
IndexLabel,
Level,
+ ListLike,
MutableMappingT,
NaPosition,
NumpySorter,
@@ -5192,11 +5193,11 @@ def rename_axis(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[True],
errors: IgnoreRaise = ...,
@@ -5206,11 +5207,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[False] = ...,
errors: IgnoreRaise = ...,
@@ -5220,11 +5221,11 @@ def drop(
@overload
def drop(
self,
- labels: IndexLabel = ...,
+ labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
- index: IndexLabel = ...,
- columns: IndexLabel = ...,
+ index: IndexLabel | ListLike = ...,
+ columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: bool = ...,
errors: IgnoreRaise = ...,
@@ -5233,11 +5234,11 @@ def drop(
def drop(
self,
- labels: IndexLabel | None = None,
+ labels: IndexLabel | ListLike = None,
*,
axis: Axis = 0,
- index: IndexLabel | None = None,
- columns: IndexLabel | None = None,
+ index: IndexLabel | ListLike = None,
+ columns: IndexLabel | ListLike = None,
level: Level | None = None,
inplace: bool = False,
errors: IgnoreRaise = "raise",
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py
index d772c908c4731..b80ed9ac50dce 100644
--- a/pandas/core/tools/timedeltas.py
+++ b/pandas/core/tools/timedeltas.py
@@ -89,7 +89,7 @@ def to_timedelta(
| Series,
unit: UnitChoices | None = None,
errors: DateTimeErrorChoices = "raise",
-) -> Timedelta | TimedeltaIndex | Series:
+) -> Timedelta | TimedeltaIndex | Series | NaTType:
"""
Convert argument to timedelta.
@@ -225,7 +225,7 @@ def to_timedelta(
def _coerce_scalar_to_timedelta_type(
r, unit: UnitChoices | None = "ns", errors: DateTimeErrorChoices = "raise"
-):
+) -> Timedelta | NaTType:
"""Convert string 'r' to a timedelta object."""
result: Timedelta | NaTType
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index 01094ba36b9dd..d3ca9c8521203 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -532,7 +532,7 @@ class ChainedAssignmentError(Warning):
)
-def _check_cacher(obj):
+def _check_cacher(obj) -> bool:
# This is a mess, selection paths that return a view set the _cacher attribute
# on the Series; most of them also set _item_cache which adds 1 to our relevant
# reference count, but iloc does not, so we have to check if we are actually
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 72c9deeb54fc7..57bc6c1379d77 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -1066,7 +1066,7 @@ class _IOWrapper:
def __init__(self, buffer: BaseBuffer) -> None:
self.buffer = buffer
- def __getattr__(self, name: str):
+ def __getattr__(self, name: str) -> Any:
return getattr(self.buffer, name)
def readable(self) -> bool:
@@ -1097,7 +1097,7 @@ def __init__(self, buffer: StringIO | TextIOBase, encoding: str = "utf-8") -> No
# overflow to the front of the bytestring the next time reading is performed
self.overflow = b""
- def __getattr__(self, attr: str):
+ def __getattr__(self, attr: str) -> Any:
return getattr(self.buffer, attr)
def read(self, n: int | None = -1) -> bytes:
diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py
index ccce60c00a9e0..cddff9a97056a 100644
--- a/pandas/io/formats/css.py
+++ b/pandas/io/formats/css.py
@@ -340,7 +340,7 @@ def _update_other_units(self, props: dict[str, str]) -> dict[str, str]:
return props
def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS) -> str:
- def _error():
+ def _error() -> str:
warnings.warn(
f"Unhandled size: {repr(in_val)}",
CSSWarning,
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 350002bf461ff..fe8702c2e16ae 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -11,12 +11,14 @@
from pandas.util._exceptions import find_stack_level
if TYPE_CHECKING:
+ from types import ModuleType
+
import google.auth
from pandas import DataFrame
-def _try_import():
+def _try_import() -> ModuleType:
# since pandas is a dependency of pandas-gbq
# we need to import on first use
msg = (
diff --git a/pyproject.toml b/pyproject.toml
index 430bb8e505df0..51d7603489cb8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -671,9 +671,7 @@ module = [
"pandas.io.sas.sas7bdat", # TODO
"pandas.io.clipboards", # TODO
"pandas.io.common", # TODO
- "pandas.io.gbq", # TODO
"pandas.io.html", # TODO
- "pandas.io.gbq", # TODO
"pandas.io.parquet", # TODO
"pandas.io.pytables", # TODO
"pandas.io.sql", # TODO
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56675 | 2023-12-29T03:56:55Z | 2023-12-29T19:51:08Z | 2023-12-29T19:51:08Z | 2023-12-29T19:51:15Z |
BUG: dictionary type astype categorical using dictionary as categories | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 129f5cedb86c2..df899469d1b2d 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -732,6 +732,7 @@ Categorical
^^^^^^^^^^^
- :meth:`Categorical.isin` raising ``InvalidIndexError`` for categorical containing overlapping :class:`Interval` values (:issue:`34974`)
- Bug in :meth:`CategoricalDtype.__eq__` returning ``False`` for unordered categorical data with mixed types (:issue:`55468`)
+- Bug when casting ``pa.dictionary`` to :class:`CategoricalDtype` using a ``pa.DictionaryArray`` as categories (:issue:`56672`)
Datetimelike
^^^^^^^^^^^^
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 8a88227ad54a3..606f0a366c7d5 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -44,7 +44,9 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
CategoricalDtype,
+ CategoricalDtypeType,
ExtensionDtype,
)
from pandas.core.dtypes.generic import (
@@ -443,24 +445,32 @@ def __init__(
values = arr
if dtype.categories is None:
- if not isinstance(values, ABCIndex):
- # in particular RangeIndex xref test_index_equal_range_categories
- values = sanitize_array(values, None)
- try:
- codes, categories = factorize(values, sort=True)
- except TypeError as err:
- codes, categories = factorize(values, sort=False)
- if dtype.ordered:
- # raise, as we don't have a sortable data structure and so
- # the user should give us one by specifying categories
- raise TypeError(
- "'values' is not ordered, please "
- "explicitly specify the categories order "
- "by passing in a categories argument."
- ) from err
-
- # we're inferring from values
- dtype = CategoricalDtype(categories, dtype.ordered)
+ if isinstance(values.dtype, ArrowDtype) and issubclass(
+ values.dtype.type, CategoricalDtypeType
+ ):
+ arr = values._pa_array.combine_chunks()
+ categories = arr.dictionary.to_pandas(types_mapper=ArrowDtype)
+ codes = arr.indices.to_numpy()
+ dtype = CategoricalDtype(categories, values.dtype.pyarrow_dtype.ordered)
+ else:
+ if not isinstance(values, ABCIndex):
+ # in particular RangeIndex xref test_index_equal_range_categories
+ values = sanitize_array(values, None)
+ try:
+ codes, categories = factorize(values, sort=True)
+ except TypeError as err:
+ codes, categories = factorize(values, sort=False)
+ if dtype.ordered:
+ # raise, as we don't have a sortable data structure and so
+ # the user should give us one by specifying categories
+ raise TypeError(
+ "'values' is not ordered, please "
+ "explicitly specify the categories order "
+ "by passing in a categories argument."
+ ) from err
+
+ # we're inferring from values
+ dtype = CategoricalDtype(categories, dtype.ordered)
elif isinstance(values.dtype, CategoricalDtype):
old_codes = extract_array(values)._codes
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..b2330f8b39642 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3229,6 +3229,22 @@ def test_factorize_chunked_dictionary():
tm.assert_index_equal(res_uniques, exp_uniques)
+def test_dictionary_astype_categorical():
+ # GH#56672
+ arrs = [
+ pa.array(np.array(["a", "x", "c", "a"])).dictionary_encode(),
+ pa.array(np.array(["a", "d", "c"])).dictionary_encode(),
+ ]
+ ser = pd.Series(ArrowExtensionArray(pa.chunked_array(arrs)))
+ result = ser.astype("category")
+ categories = pd.Index(["a", "x", "c", "d"], dtype=ArrowDtype(pa.string()))
+ expected = pd.Series(
+ ["a", "x", "c", "a", "a", "d", "c"],
+ dtype=pd.CategoricalDtype(categories=categories),
+ )
+ tm.assert_series_equal(result, expected)
+
+
def test_arrow_floordiv():
# GH 55561
a = pd.Series([-7], dtype="int64[pyarrow]")
| Currently, we use a dictionary array as categories, which is weird, this just uses the underlying dictionary and extracts the codes, which should be fine for us. The dictionary array causes all kinds of trouble when sorting and doing similar things
| https://api.github.com/repos/pandas-dev/pandas/pulls/56672 | 2023-12-28T22:39:39Z | 2024-01-03T22:49:01Z | 2024-01-03T22:49:00Z | 2024-01-03T22:49:04Z |
STY: Enable ruff pytest checks | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 6033bda99e8c8..73ac14f1ed5ce 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -272,13 +272,6 @@ repos:
language: python
types: [rst]
files: ^doc/source/(development|reference)/
- - id: unwanted-patterns-bare-pytest-raises
- name: Check for use of bare pytest raises
- language: python
- entry: python scripts/validate_unwanted_patterns.py --validation-type="bare_pytest_raises"
- types: [python]
- files: ^pandas/tests/
- exclude: ^pandas/tests/extension/
- id: unwanted-patterns-private-function-across-module
name: Check for use of private functions across modules
language: python
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 4a3fb5c2916c6..16b437b9a4723 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1971,6 +1971,6 @@ def warsaw(request) -> str:
return request.param
-@pytest.fixture()
+@pytest.fixture
def arrow_string_storage():
return ("pyarrow", "pyarrow_numpy")
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index b4e8d09c18163..75259cb7e2f05 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1385,7 +1385,6 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit):
"SemiMonthBegin",
"Week",
("Week", {"weekday": 3}),
- "Week",
("Week", {"weekday": 6}),
"BusinessDay",
"BDay",
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index 41d9db7335957..cff8afaa17516 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -291,12 +291,12 @@ def test_set_categories(self):
(["a", "b", "c"], ["a", "b"], ["a", "b"]),
(["a", "b", "c"], ["a", "b"], ["b", "a"]),
(["b", "a", "c"], ["a", "b"], ["a", "b"]),
- (["b", "a", "c"], ["a", "b"], ["a", "b"]),
+ (["b", "a", "c"], ["a", "b"], ["b", "a"]),
# Introduce NaNs
(["a", "b", "c"], ["a", "b"], ["a"]),
(["a", "b", "c"], ["a", "b"], ["b"]),
(["b", "a", "c"], ["a", "b"], ["a"]),
- (["b", "a", "c"], ["a", "b"], ["a"]),
+ (["b", "a", "c"], ["a", "b"], ["b"]),
# No overlap
(["a", "b", "c"], ["a", "b"], ["d", "e"]),
],
diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py
index f2f2851c22794..ec1d501ddba16 100644
--- a/pandas/tests/arrays/categorical/test_dtypes.py
+++ b/pandas/tests/arrays/categorical/test_dtypes.py
@@ -73,12 +73,12 @@ def test_set_dtype_new_categories(self):
(["a", "b", "c"], ["a", "b"], ["a", "b"]),
(["a", "b", "c"], ["a", "b"], ["b", "a"]),
(["b", "a", "c"], ["a", "b"], ["a", "b"]),
- (["b", "a", "c"], ["a", "b"], ["a", "b"]),
+ (["b", "a", "c"], ["a", "b"], ["b", "a"]),
# Introduce NaNs
(["a", "b", "c"], ["a", "b"], ["a"]),
(["a", "b", "c"], ["a", "b"], ["b"]),
(["b", "a", "c"], ["a", "b"], ["a"]),
- (["b", "a", "c"], ["a", "b"], ["a"]),
+ (["b", "a", "c"], ["a", "b"], ["b"]),
# No overlap
(["a", "b", "c"], ["a", "b"], ["d", "e"]),
],
diff --git a/pandas/tests/arrays/masked/test_function.py b/pandas/tests/arrays/masked/test_function.py
index 4c7bd6e293ef4..d5ea60ecb754d 100644
--- a/pandas/tests/arrays/masked/test_function.py
+++ b/pandas/tests/arrays/masked/test_function.py
@@ -21,7 +21,7 @@ def data(request):
return request.param
-@pytest.fixture()
+@pytest.fixture
def numpy_dtype(data):
"""
Fixture returning numpy dtype from 'data' input array.
diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index ffc93b4e4f176..f84d03e851621 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -433,9 +433,6 @@ def test_ufuncs(ufunc, arr):
[
(SparseArray([0, 0, 0]), np.array([0, 1, 2])),
(SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
- (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
- (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
- (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),
],
)
@pytest.mark.parametrize("ufunc", [np.add, np.greater])
diff --git a/pandas/tests/arrays/string_/test_string_arrow.py b/pandas/tests/arrays/string_/test_string_arrow.py
index d7811b6fed883..405c1c217b04d 100644
--- a/pandas/tests/arrays/string_/test_string_arrow.py
+++ b/pandas/tests/arrays/string_/test_string_arrow.py
@@ -220,22 +220,22 @@ def test_setitem_invalid_indexer_raises():
arr = ArrowStringArray(pa.array(list("abcde")))
- with pytest.raises(IndexError, match=None):
+ with tm.external_error_raised(IndexError):
arr[5] = "foo"
- with pytest.raises(IndexError, match=None):
+ with tm.external_error_raised(IndexError):
arr[-6] = "foo"
- with pytest.raises(IndexError, match=None):
+ with tm.external_error_raised(IndexError):
arr[[0, 5]] = "foo"
- with pytest.raises(IndexError, match=None):
+ with tm.external_error_raised(IndexError):
arr[[0, -6]] = "foo"
- with pytest.raises(IndexError, match=None):
+ with tm.external_error_raised(IndexError):
arr[[True, True, False]] = "foo"
- with pytest.raises(ValueError, match=None):
+ with tm.external_error_raised(ValueError):
arr[[0, 1]] = ["foo", "bar", "baz"]
diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py
index 96263f498935b..a84fefebf044c 100644
--- a/pandas/tests/arrays/test_array.py
+++ b/pandas/tests/arrays/test_array.py
@@ -29,7 +29,7 @@
)
-@pytest.mark.parametrize("dtype_unit", ["M8[h]", "M8[m]", "m8[h]", "M8[m]"])
+@pytest.mark.parametrize("dtype_unit", ["M8[h]", "M8[m]", "m8[h]"])
def test_dt64_array(dtype_unit):
# PR 53817
dtype_var = np.dtype(dtype_unit)
diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py
index 615b024bd06bf..400fb8e03c18c 100644
--- a/pandas/tests/copy_view/test_internals.py
+++ b/pandas/tests/copy_view/test_internals.py
@@ -83,7 +83,6 @@ def test_switch_options():
([0, 1, 2], np.array([[-1, -2, -3], [-4, -5, -6], [-4, -5, -6]]).T),
([1, 2], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
- ([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
],
)
def test_iset_splits_blocks_inplace(using_copy_on_write, locs, arr, dtype):
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index 7105755df6f88..c205f35b0ced8 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -531,7 +531,6 @@ def test_array_equivalent_different_dtype_but_equal():
(fix_now, fix_utcnow),
(fix_now.to_datetime64(), fix_utcnow),
(fix_now.to_pydatetime(), fix_utcnow),
- (fix_now, fix_utcnow),
(fix_now.to_datetime64(), fix_utcnow.to_pydatetime()),
(fix_now.to_pydatetime(), fix_utcnow.to_pydatetime()),
],
diff --git a/pandas/tests/extension/base/dim2.py b/pandas/tests/extension/base/dim2.py
index 132cda5a94ed0..4da9fe8917d55 100644
--- a/pandas/tests/extension/base/dim2.py
+++ b/pandas/tests/extension/base/dim2.py
@@ -90,9 +90,9 @@ def test_reshape(self, data):
assert arr2d.shape == (data.size, 1)
assert len(arr2d) == len(data)
- with pytest.raises(ValueError):
+ with tm.external_error_raised(ValueError):
data.reshape((data.size, 2))
- with pytest.raises(ValueError):
+ with tm.external_error_raised(ValueError):
data.reshape(data.size, 2)
def test_getitem_2d(self, data):
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py
index 5f0c1b960a475..1f89c7ad9d4e4 100644
--- a/pandas/tests/extension/base/getitem.py
+++ b/pandas/tests/extension/base/getitem.py
@@ -394,7 +394,7 @@ def test_take_non_na_fill_value(self, data_missing):
tm.assert_extension_array_equal(result, expected)
def test_take_pandas_style_negative_raises(self, data, na_value):
- with pytest.raises(ValueError, match=""):
+ with tm.external_error_raised(ValueError):
data.take([0, -2], fill_value=na_value, allow_fill=True)
@pytest.mark.parametrize("allow_fill", [True, False])
diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py
index 4a2942776b25e..ba756b471eb8b 100644
--- a/pandas/tests/extension/base/setitem.py
+++ b/pandas/tests/extension/base/setitem.py
@@ -209,7 +209,8 @@ def test_setitem_integer_array(self, data, idx, box_in_series):
[0, 1, 2, pd.NA], True, marks=pytest.mark.xfail(reason="GH-31948")
),
(pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
- (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
+ # TODO: change False to True?
+ (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False), # noqa: PT014
],
ids=["list-False", "list-True", "integer-array-False", "integer-array-True"],
)
@@ -332,7 +333,7 @@ def test_setitem_loc_iloc_slice(self, data):
def test_setitem_slice_mismatch_length_raises(self, data):
arr = data[:5]
- with pytest.raises(ValueError):
+ with tm.external_error_raised(ValueError):
arr[:1] = arr[:2]
def test_setitem_slice_array(self, data):
@@ -342,7 +343,7 @@ def test_setitem_slice_array(self, data):
def test_setitem_scalar_key_sequence_raise(self, data):
arr = data[:5].copy()
- with pytest.raises(ValueError):
+ with tm.external_error_raised(ValueError):
arr[0] = arr[[0, 1]]
def test_setitem_preserves_views(self, data):
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 9de4f17a27333..50f2fe03cfa13 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -355,7 +355,7 @@ def test_setitem_integer_array(self, data, idx, box_in_series, request):
[0, 1, 2, pd.NA], True, marks=pytest.mark.xfail(reason="GH-31948")
),
(pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
- (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
+ (pd.array([0, 1, 2, pd.NA], dtype="Int64"), True),
],
ids=["list-False", "list-True", "integer-array-False", "integer-array-True"],
)
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index 9a0cb67a87f30..0893c6231197e 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -373,19 +373,6 @@ def test_setitem_mask(self, data, mask, box_in_series):
def test_setitem_integer_array(self, data, idx, box_in_series):
super().test_setitem_integer_array(data, idx, box_in_series)
- @pytest.mark.parametrize(
- "idx, box_in_series",
- [
- ([0, 1, 2, pd.NA], False),
- pytest.param([0, 1, 2, pd.NA], True, marks=pytest.mark.xfail),
- (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
- (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
- ],
- ids=["list-False", "list-True", "integer-array-False", "integer-array-True"],
- )
- def test_setitem_integer_with_missing_raises(self, data, idx, box_in_series):
- super().test_setitem_integer_with_missing_raises(data, idx, box_in_series)
-
@skip_nested
def test_setitem_slice(self, data, box_in_series):
super().test_setitem_slice(data, box_in_series)
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index 03f179fdd261e..2efcc192aa15b 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -70,7 +70,7 @@ def gen(count):
for _ in range(count):
yield SparseArray(make_data(request.param), fill_value=request.param)
- yield gen
+ return gen
@pytest.fixture(params=[0, np.nan])
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index eab8dbd2787f7..e7f2c410bf4ac 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -867,7 +867,7 @@ class IntegerArrayNoCopy(pd.core.arrays.IntegerArray):
# GH 42501
def copy(self):
- assert False
+ raise NotImplementedError
class Int16DtypeNoCopy(pd.Int16Dtype):
diff --git a/pandas/tests/frame/methods/test_explode.py b/pandas/tests/frame/methods/test_explode.py
index 5cd54db62d783..ca9764c023244 100644
--- a/pandas/tests/frame/methods/test_explode.py
+++ b/pandas/tests/frame/methods/test_explode.py
@@ -38,10 +38,6 @@ def test_error():
[],
"column must be nonempty",
),
- (
- list("AC"),
- "columns must have matching element counts",
- ),
],
)
def test_error_multi_columns(input_subset, error_message):
diff --git a/pandas/tests/frame/methods/test_filter.py b/pandas/tests/frame/methods/test_filter.py
index 9d5e6876bb08c..382615aaef627 100644
--- a/pandas/tests/frame/methods/test_filter.py
+++ b/pandas/tests/frame/methods/test_filter.py
@@ -100,7 +100,6 @@ def test_filter_regex_search(self, float_frame):
@pytest.mark.parametrize(
"name,expected",
[
- ("a", DataFrame({"a": [1, 2]})),
("a", DataFrame({"a": [1, 2]})),
("あ", DataFrame({"あ": [3, 4]})),
],
@@ -112,9 +111,9 @@ def test_filter_unicode(self, name, expected):
tm.assert_frame_equal(df.filter(like=name), expected)
tm.assert_frame_equal(df.filter(regex=name), expected)
- @pytest.mark.parametrize("name", ["a", "a"])
- def test_filter_bytestring(self, name):
+ def test_filter_bytestring(self):
# GH13101
+ name = "a"
df = DataFrame({b"a": [1, 2], b"b": [3, 4]})
expected = DataFrame({b"a": [1, 2]})
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index d2ec84bc9371f..2a889efe79064 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -452,19 +452,16 @@ def f(val):
("mid",),
("mid", "btm"),
("mid", "btm", "top"),
- ("mid",),
("mid", "top"),
("mid", "top", "btm"),
("btm",),
("btm", "mid"),
("btm", "mid", "top"),
- ("btm",),
("btm", "top"),
("btm", "top", "mid"),
("top",),
("top", "mid"),
("top", "mid", "btm"),
- ("top",),
("top", "btm"),
("top", "btm", "mid"),
],
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index 9d07b8ab2288f..a77e063b5f353 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -27,7 +27,7 @@
import pandas._testing as tm
-@pytest.fixture()
+@pytest.fixture
def multiindex_df():
levels = [["A", ""], ["B", "b"]]
return DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index aefb0377d1bf4..d44de380d243a 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -1555,7 +1555,7 @@ def test_constructor_mixed_type_rows(self):
"tuples,lists",
[
((), []),
- ((()), []),
+ (((),), [[]]),
(((), ()), [(), ()]),
(((), ()), [[], []]),
(([], []), [[], []]),
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index a498296e09c52..0a869d8f94f47 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -1187,7 +1187,7 @@ def df(self):
by backticks. The last two columns cannot be escaped by backticks
and should raise a ValueError.
"""
- yield DataFrame(
+ return DataFrame(
{
"A": [1, 2, 3],
"B B": [3, 2, 1],
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 5aaa11b848be4..fa233619ad3a3 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1866,7 +1866,6 @@ def test_df_empty_min_count_1(self, opname, dtype, exp_dtype):
[
("sum", "Int8", 0, ("Int32" if is_windows_np2_or_is32 else "Int64")),
("prod", "Int8", 1, ("Int32" if is_windows_np2_or_is32 else "Int64")),
- ("prod", "Int8", 1, ("Int32" if is_windows_np2_or_is32 else "Int64")),
("sum", "Int64", 0, "Int64"),
("prod", "Int64", 1, "Int64"),
("sum", "UInt8", 0, ("UInt32" if is_windows_np2_or_is32 else "UInt64")),
diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py
index 331dbd85e0f36..2745f7c2b8d0f 100644
--- a/pandas/tests/groupby/conftest.py
+++ b/pandas/tests/groupby/conftest.py
@@ -92,7 +92,7 @@ def three_group():
)
-@pytest.fixture()
+@pytest.fixture
def slice_test_df():
data = [
[0, "a", "a0_at_0"],
@@ -108,7 +108,7 @@ def slice_test_df():
return df.set_index("Index")
-@pytest.fixture()
+@pytest.fixture
def slice_test_grouped(slice_test_df):
return slice_test_df.groupby("Group", as_index=False)
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index a2cc7fd782396..3e1a244a8a72e 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -647,7 +647,7 @@ def test_dataframe_categorical_ordered_observed_sort(ordered, observed, sort):
f"for (ordered={ordered}, observed={observed}, sort={sort})\n"
f"Result:\n{result}"
)
- assert False, msg
+ pytest.fail(msg)
def test_datetime():
diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py
index ca097bc2be8bb..768ab2db5cea5 100644
--- a/pandas/tests/groupby/test_groupby_dropna.py
+++ b/pandas/tests/groupby/test_groupby_dropna.py
@@ -410,7 +410,6 @@ def test_groupby_drop_nan_with_multi_index():
"UInt64",
"Int64",
"Float32",
- "Int64",
"Float64",
"category",
"string",
diff --git a/pandas/tests/indexes/datetimelike_/test_sort_values.py b/pandas/tests/indexes/datetimelike_/test_sort_values.py
index a2c349c8b0ef6..bfef0faebeebf 100644
--- a/pandas/tests/indexes/datetimelike_/test_sort_values.py
+++ b/pandas/tests/indexes/datetimelike_/test_sort_values.py
@@ -185,10 +185,6 @@ def test_sort_values_without_freq_timedeltaindex(self):
@pytest.mark.parametrize(
"index_dates,expected_dates",
[
- (
- ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
- ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
- ),
(
["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py
index 8456e6a7acba5..38e0920b7004e 100644
--- a/pandas/tests/indexes/multi/test_constructors.py
+++ b/pandas/tests/indexes/multi/test_constructors.py
@@ -304,7 +304,6 @@ def test_from_arrays_empty():
(1, 2),
([1], 2),
(1, [2]),
- "a",
("a",),
("a", "b"),
(["a"], "b"),
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 66dd893df51de..1806242b83126 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -1158,7 +1158,6 @@ def test_array_to_slice_conversion(self, arr, slc):
[-1],
[-1, -2, -3],
[-10],
- [-1],
[-1, 0, 1, 2],
[-2, 0, 2, 4],
[1, 0, -1],
diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py
index db436d8283b99..8bf9aa4ac04d3 100644
--- a/pandas/tests/io/formats/test_css.py
+++ b/pandas/tests/io/formats/test_css.py
@@ -243,7 +243,6 @@ def test_css_none_absent(style, equiv):
("02.54cm", "72pt"),
("25.4mm", "72pt"),
("101.6q", "72pt"),
- ("101.6q", "72pt"),
],
)
@pytest.mark.parametrize("relative_to", [None, "16pt"]) # invariant to inherited size
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 98f1e0245b353..4c8cd4b6a2b8e 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -771,7 +771,7 @@ def df_with_symbols(self):
"""Dataframe with special characters for testing chars escaping."""
a = "a"
b = "b"
- yield DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}})
+ return DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}})
def test_to_latex_escape_false(self, df_with_symbols):
result = df_with_symbols.to_latex(escape=False)
@@ -1010,7 +1010,7 @@ class TestToLatexMultiindex:
@pytest.fixture
def multiindex_frame(self):
"""Multiindex dataframe for testing multirow LaTeX macros."""
- yield DataFrame.from_dict(
+ return DataFrame.from_dict(
{
("c1", 0): Series({x: x for x in range(4)}),
("c1", 1): Series({x: x + 4 for x in range(4)}),
@@ -1023,7 +1023,7 @@ def multiindex_frame(self):
@pytest.fixture
def multicolumn_frame(self):
"""Multicolumn dataframe for testing multicolumn LaTeX macros."""
- yield DataFrame(
+ return DataFrame(
{
("c1", 0): {x: x for x in range(5)},
("c1", 1): {x: x + 5 for x in range(5)},
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index cc101bb9c8b6d..d5ea470af79d6 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -179,7 +179,6 @@ def test_as_json_table_type_string_data(self, str_data):
pd.Categorical([1]),
pd.Series(pd.Categorical([1])),
pd.CategoricalIndex([1]),
- pd.Categorical([1]),
],
)
def test_as_json_table_type_categorical_data(self, cat_data):
diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py
index a7a8d031da215..5e31b4c6b644d 100644
--- a/pandas/tests/io/parser/common/test_file_buffer_url.py
+++ b/pandas/tests/io/parser/common/test_file_buffer_url.py
@@ -425,7 +425,7 @@ def test_context_manager(all_parsers, datapath):
try:
with reader:
next(reader)
- assert False
+ raise AssertionError
except AssertionError:
assert reader.handles.handle.closed
@@ -446,7 +446,7 @@ def test_context_manageri_user_provided(all_parsers, datapath):
try:
with reader:
next(reader)
- assert False
+ raise AssertionError
except AssertionError:
assert not reader.handles.handle.closed
diff --git a/pandas/tests/io/parser/usecols/test_strings.py b/pandas/tests/io/parser/usecols/test_strings.py
index d4ade41d38465..0d51c2cb3cdb4 100644
--- a/pandas/tests/io/parser/usecols/test_strings.py
+++ b/pandas/tests/io/parser/usecols/test_strings.py
@@ -74,8 +74,7 @@ def test_usecols_with_mixed_encoding_strings(all_parsers, usecols):
parser.read_csv(StringIO(data), usecols=usecols)
-@pytest.mark.parametrize("usecols", [["あああ", "いい"], ["あああ", "いい"]])
-def test_usecols_with_multi_byte_characters(all_parsers, usecols):
+def test_usecols_with_multi_byte_characters(all_parsers):
data = """あああ,いい,ううう,ええええ
0.056674973,8,True,a
2.613230982,2,False,b
@@ -92,5 +91,5 @@ def test_usecols_with_multi_byte_characters(all_parsers, usecols):
}
expected = DataFrame(exp_data)
- result = parser.read_csv(StringIO(data), usecols=usecols)
+ result = parser.read_csv(StringIO(data), usecols=["あああ", "いい"])
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py
index b07fb3ddd3ac8..b78a503a2b8a3 100644
--- a/pandas/tests/io/pytables/test_compat.py
+++ b/pandas/tests/io/pytables/test_compat.py
@@ -36,7 +36,7 @@ def pytables_hdf5_file(tmp_path):
t.row[key] = value
t.row.append()
- yield path, objname, pd.DataFrame(testsamples)
+ return path, objname, pd.DataFrame(testsamples)
class TestReadPyTablesHDF5:
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 8fc02cc7799ed..a6967732cf702 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1327,7 +1327,7 @@ def test_use_nullable_dtypes_not_supported(self, fp):
def test_close_file_handle_on_read_error(self):
with tm.ensure_clean("test.parquet") as path:
pathlib.Path(path).write_bytes(b"breakit")
- with pytest.raises(Exception, match=""): # Not important which exception
+ with tm.external_error_raised(Exception): # Not important which exception
read_parquet(path, engine="fastparquet")
# The next line raises an error on Windows if the file is still open
pathlib.Path(path).unlink(missing_ok=False)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 6645aefd4f0a7..2ddbbaa1bf17c 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -620,13 +620,13 @@ def mysql_pymysql_engine():
def mysql_pymysql_engine_iris(mysql_pymysql_engine, iris_path):
create_and_load_iris(mysql_pymysql_engine, iris_path)
create_and_load_iris_view(mysql_pymysql_engine)
- yield mysql_pymysql_engine
+ return mysql_pymysql_engine
@pytest.fixture
def mysql_pymysql_engine_types(mysql_pymysql_engine, types_data):
create_and_load_types(mysql_pymysql_engine, types_data, "mysql")
- yield mysql_pymysql_engine
+ return mysql_pymysql_engine
@pytest.fixture
@@ -667,13 +667,13 @@ def postgresql_psycopg2_engine():
def postgresql_psycopg2_engine_iris(postgresql_psycopg2_engine, iris_path):
create_and_load_iris(postgresql_psycopg2_engine, iris_path)
create_and_load_iris_view(postgresql_psycopg2_engine)
- yield postgresql_psycopg2_engine
+ return postgresql_psycopg2_engine
@pytest.fixture
def postgresql_psycopg2_engine_types(postgresql_psycopg2_engine, types_data):
create_and_load_types(postgresql_psycopg2_engine, types_data, "postgres")
- yield postgresql_psycopg2_engine
+ return postgresql_psycopg2_engine
@pytest.fixture
@@ -713,7 +713,7 @@ def postgresql_adbc_iris(postgresql_adbc_conn, iris_path):
except mgr.ProgrammingError: # note arrow-adbc issue 1022
conn.rollback()
create_and_load_iris_view(conn)
- yield conn
+ return conn
@pytest.fixture
@@ -730,7 +730,7 @@ def postgresql_adbc_types(postgresql_adbc_conn, types_data):
create_and_load_types_postgresql(conn, new_data)
- yield conn
+ return conn
@pytest.fixture
@@ -784,7 +784,7 @@ def sqlite_str_iris(sqlite_str, iris_path):
def sqlite_engine_iris(sqlite_engine, iris_path):
create_and_load_iris(sqlite_engine, iris_path)
create_and_load_iris_view(sqlite_engine)
- yield sqlite_engine
+ return sqlite_engine
@pytest.fixture
@@ -805,7 +805,7 @@ def sqlite_str_types(sqlite_str, types_data):
@pytest.fixture
def sqlite_engine_types(sqlite_engine, types_data):
create_and_load_types(sqlite_engine, types_data, "sqlite")
- yield sqlite_engine
+ return sqlite_engine
@pytest.fixture
@@ -845,7 +845,7 @@ def sqlite_adbc_iris(sqlite_adbc_conn, iris_path):
except mgr.ProgrammingError:
conn.rollback()
create_and_load_iris_view(conn)
- yield conn
+ return conn
@pytest.fixture
@@ -867,7 +867,7 @@ def sqlite_adbc_types(sqlite_adbc_conn, types_data):
create_and_load_types_sqlite3(conn, new_data)
conn.commit()
- yield conn
+ return conn
@pytest.fixture
@@ -881,14 +881,14 @@ def sqlite_buildin():
def sqlite_buildin_iris(sqlite_buildin, iris_path):
create_and_load_iris_sqlite3(sqlite_buildin, iris_path)
create_and_load_iris_view(sqlite_buildin)
- yield sqlite_buildin
+ return sqlite_buildin
@pytest.fixture
def sqlite_buildin_types(sqlite_buildin, types_data):
types_data = [tuple(entry.values()) for entry in types_data]
create_and_load_types_sqlite3(sqlite_buildin, types_data)
- yield sqlite_buildin
+ return sqlite_buildin
mysql_connectable = [
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index fcb5b65e59402..ec9ad8af1239e 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -801,7 +801,7 @@ def test_var_masked_array(self, ddof, exp):
assert result == result_numpy_dtype
assert result == exp
- @pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]"))
+ @pytest.mark.parametrize("dtype", ("m8[ns]", "M8[ns]", "M8[ns, UTC]"))
def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
# covers GH#11245
assert Series([], dtype=dtype).min(skipna=skipna) is NaT
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 21a38c43f4294..00f151dfc3e67 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1635,7 +1635,6 @@ def test_merge_incompat_dtypes_are_ok(self, df1_vals, df2_vals):
(Series([1, 2], dtype="int32"), ["a", "b", "c"]),
([0, 1, 2], ["0", "1", "2"]),
([0.0, 1.0, 2.0], ["0", "1", "2"]),
- ([0, 1, 2], ["0", "1", "2"]),
(
pd.date_range("1/1/2011", periods=2, freq="D"),
["2011-01-01", "2011-01-02"],
diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index cb046e0133245..e352e2601cef3 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -146,7 +146,6 @@ def test_round_nat(klass, method, freq):
"utcnow",
"utcoffset",
"utctimetuple",
- "timestamp",
],
)
def test_nat_methods_raise(method):
diff --git a/pandas/tests/series/methods/test_size.py b/pandas/tests/series/methods/test_size.py
index 20a454996fa44..043e4b66dbf16 100644
--- a/pandas/tests/series/methods/test_size.py
+++ b/pandas/tests/series/methods/test_size.py
@@ -10,8 +10,6 @@
({"a": 1, "b": 2, "c": 3}, None, 3),
([1, 2, 3], ["x", "y", "z"], 3),
([1, 2, 3, 4, 5], ["x", "y", "z", "w", "n"], 5),
- ([1, 2, 3], None, 3),
- ([1, 2, 3], ["x", "y", "z"], 3),
([1, 2, 3, 4], ["x", "y", "z", "w"], 4),
],
)
diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py
index 77d008c650264..7ebcbdc7a8533 100644
--- a/pandas/tests/strings/test_extract.py
+++ b/pandas/tests/strings/test_extract.py
@@ -548,7 +548,6 @@ def test_extractall_single_group_with_quantifier(any_string_dtype):
(["a3", "b3", "d4c2"], (None,)),
(["a3", "b3", "d4c2"], ("i1", "i2")),
(["a3", "b3", "d4c2"], (None, "i2")),
- (["a3", "b3", "d4c2"], ("i1", "i2")),
],
)
def test_extractall_no_matches(data, names, any_string_dtype):
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index 95d0953301a42..ed125ece349a9 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -748,7 +748,6 @@ def test_nancov(self):
("arr_bool", False),
("arr_str", False),
("arr_utf", False),
- ("arr_complex", False),
("arr_complex_nan", False),
("arr_nan_nanj", False),
("arr_nan_infj", True),
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 4a012f34ddc3b..46b4b97c437b6 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -3043,7 +3043,6 @@ def test_day_not_in_month_raise_value(self, cache, arg, format, msg):
[
["2015-02-29", None],
["2015-02-29", "%Y-%m-%d"],
- ["2015-02-29", "%Y-%m-%d"],
["2015-04-31", "%Y-%m-%d"],
],
)
diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py
index 0d37273e89092..edfc1973a2bd9 100644
--- a/pandas/tests/tseries/frequencies/test_inference.py
+++ b/pandas/tests/tseries/frequencies/test_inference.py
@@ -499,7 +499,6 @@ def test_series_datetime_index(freq):
"YE@OCT",
"YE@NOV",
"YE@DEC",
- "YE@JAN",
"WOM@1MON",
"WOM@2MON",
"WOM@3MON",
diff --git a/pandas/tests/tslibs/test_to_offset.py b/pandas/tests/tslibs/test_to_offset.py
index ef68408305232..204775347e47a 100644
--- a/pandas/tests/tslibs/test_to_offset.py
+++ b/pandas/tests/tslibs/test_to_offset.py
@@ -24,7 +24,6 @@
("15ms500us", offsets.Micro(15500)),
("10s75ms", offsets.Milli(10075)),
("1s0.25ms", offsets.Micro(1000250)),
- ("1s0.25ms", offsets.Micro(1000250)),
("2800ns", offsets.Nano(2800)),
("2SME", offsets.SemiMonthEnd(2)),
("2SME-16", offsets.SemiMonthEnd(2, day_of_month=16)),
diff --git a/pyproject.toml b/pyproject.toml
index f693048adb60c..ebdf9deb034b5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -212,6 +212,8 @@ select = [
"INT",
# pylint
"PL",
+ # flake8-pytest-style
+ "PT",
# misc lints
"PIE",
# flake8-pyi
@@ -304,6 +306,24 @@ ignore = [
"PERF102",
# try-except-in-loop, becomes useless in Python 3.11
"PERF203",
+ # pytest-missing-fixture-name-underscore
+ "PT004",
+ # pytest-incorrect-fixture-name-underscore
+ "PT005",
+ # pytest-parametrize-names-wrong-type
+ "PT006",
+ # pytest-parametrize-values-wrong-type
+ "PT007",
+ # pytest-patch-with-lambda
+ "PT008",
+ # pytest-raises-with-multiple-statements
+ "PT012",
+ # pytest-assert-in-except
+ "PT017",
+ # pytest-composite-assertion
+ "PT018",
+ # pytest-fixture-param-without-value
+ "PT019",
# The following rules may cause conflicts when used with the formatter:
"ISC001",
@@ -351,6 +371,10 @@ exclude = [
# Keep this one enabled
"pandas/_typing.py" = ["TCH"]
+[tool.ruff.lint.flake8-pytest-style]
+fixture-parentheses = false
+mark-parentheses = false
+
[tool.pylint.messages_control]
max-line-length = 88
disable = [
diff --git a/scripts/tests/test_validate_unwanted_patterns.py b/scripts/tests/test_validate_unwanted_patterns.py
index bef9d369a0a3c..4c433d03aff4d 100644
--- a/scripts/tests/test_validate_unwanted_patterns.py
+++ b/scripts/tests/test_validate_unwanted_patterns.py
@@ -5,154 +5,6 @@
from scripts import validate_unwanted_patterns
-class TestBarePytestRaises:
- @pytest.mark.parametrize(
- "data",
- [
- (
- """
- with pytest.raises(ValueError, match="foo"):
- pass
- """
- ),
- (
- """
- # with pytest.raises(ValueError, match="foo"):
- # pass
- """
- ),
- (
- """
- # with pytest.raises(ValueError):
- # pass
- """
- ),
- (
- """
- with pytest.raises(
- ValueError,
- match="foo"
- ):
- pass
- """
- ),
- ],
- )
- def test_pytest_raises(self, data) -> None:
- fd = io.StringIO(data.strip())
- result = list(validate_unwanted_patterns.bare_pytest_raises(fd))
- assert result == []
-
- @pytest.mark.parametrize(
- "data, expected",
- [
- (
- (
- """
- with pytest.raises(ValueError):
- pass
- """
- ),
- [
- (
- 1,
- (
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' "
- "as well the exception."
- ),
- ),
- ],
- ),
- (
- (
- """
- with pytest.raises(ValueError, match="foo"):
- with pytest.raises(ValueError):
- pass
- pass
- """
- ),
- [
- (
- 2,
- (
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' "
- "as well the exception."
- ),
- ),
- ],
- ),
- (
- (
- """
- with pytest.raises(ValueError):
- with pytest.raises(ValueError, match="foo"):
- pass
- pass
- """
- ),
- [
- (
- 1,
- (
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' "
- "as well the exception."
- ),
- ),
- ],
- ),
- (
- (
- """
- with pytest.raises(
- ValueError
- ):
- pass
- """
- ),
- [
- (
- 1,
- (
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' "
- "as well the exception."
- ),
- ),
- ],
- ),
- (
- (
- """
- with pytest.raises(
- ValueError,
- # match = "foo"
- ):
- pass
- """
- ),
- [
- (
- 1,
- (
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' "
- "as well the exception."
- ),
- ),
- ],
- ),
- ],
- )
- def test_pytest_raises_raises(self, data, expected) -> None:
- fd = io.StringIO(data.strip())
- result = list(validate_unwanted_patterns.bare_pytest_raises(fd))
- assert result == expected
-
-
class TestStringsWithWrongPlacedWhitespace:
@pytest.mark.parametrize(
"data",
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index 0d724779abfda..ee7f9226a7090 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -95,65 +95,6 @@ def _get_literal_string_prefix_len(token_string: str) -> int:
return 0
-def bare_pytest_raises(file_obj: IO[str]) -> Iterable[tuple[int, str]]:
- """
- Test Case for bare pytest raises.
-
- For example, this is wrong:
-
- >>> with pytest.raise(ValueError):
- ... # Some code that raises ValueError
-
- And this is what we want instead:
-
- >>> with pytest.raise(ValueError, match="foo"):
- ... # Some code that raises ValueError
-
- Parameters
- ----------
- file_obj : IO
- File-like object containing the Python code to validate.
-
- Yields
- ------
- line_number : int
- Line number of unconcatenated string.
- msg : str
- Explanation of the error.
-
- Notes
- -----
- GH #23922
- """
- contents = file_obj.read()
- tree = ast.parse(contents)
-
- for node in ast.walk(tree):
- if not isinstance(node, ast.Call):
- continue
-
- try:
- if not (node.func.value.id == "pytest" and node.func.attr == "raises"):
- continue
- except AttributeError:
- continue
-
- if not node.keywords:
- yield (
- node.lineno,
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' as well the exception.",
- )
- # Means that there are arguments that are being passed in,
- # now we validate that `match` is one of the passed in arguments
- elif not any(keyword.arg == "match" for keyword in node.keywords):
- yield (
- node.lineno,
- "Bare pytests raise have been found. "
- "Please pass in the argument 'match' as well the exception.",
- )
-
-
PRIVATE_FUNCTIONS_ALLOWED = {"sys._getframe"} # no known alternative
@@ -457,7 +398,6 @@ def main(
if __name__ == "__main__":
available_validation_types: list[str] = [
- "bare_pytest_raises",
"private_function_across_module",
"private_import_across_module",
"strings_with_wrong_placed_whitespace",
diff --git a/web/tests/test_pandas_web.py b/web/tests/test_pandas_web.py
index a5f76875dfe23..aacdfbcd6d26e 100644
--- a/web/tests/test_pandas_web.py
+++ b/web/tests/test_pandas_web.py
@@ -30,7 +30,7 @@ def context() -> dict:
}
-@pytest.fixture(scope="function")
+@pytest.fixture
def mock_response(monkeypatch, request) -> None:
def mocked_resp(*args, **kwargs):
status_code, response = request.param
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56671 | 2023-12-28T22:26:00Z | 2024-01-05T20:23:52Z | 2024-01-05T20:23:52Z | 2024-01-05T20:23:56Z |
Backport PR #56664 on branch 2.2.x (CI: Run jobs on 2.2.x branch) | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index b49b9a67c4743..8e29d56f47dcf 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index da232404e6ff5..73acd9acc129a 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -4,13 +4,13 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
tags:
- '*'
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml
index 04d8b8e006985..d59ddf272f705 100644
--- a/.github/workflows/package-checks.yml
+++ b/.github/workflows/package-checks.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
types: [ labeled, opened, synchronize, reopened ]
permissions:
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 6ca4d19196874..12e645dc9da81 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
paths-ignore:
- "doc/**"
- "web/**"
| Backport PR #56664: CI: Run jobs on 2.2.x branch | https://api.github.com/repos/pandas-dev/pandas/pulls/56669 | 2023-12-28T21:45:24Z | 2023-12-28T22:43:47Z | 2023-12-28T22:43:47Z | 2023-12-28T22:43:47Z |
Backport PR #56654 on branch 2.2.x (BUG: assert_series_equal not properly respecting check-dtype) | diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 800b03707540f..d0f38c85868d4 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -949,9 +949,15 @@ def assert_series_equal(
obj=str(obj),
)
else:
+ # convert both to NumPy if not, check_dtype would raise earlier
+ lv, rv = left_values, right_values
+ if isinstance(left_values, ExtensionArray):
+ lv = left_values.to_numpy()
+ if isinstance(right_values, ExtensionArray):
+ rv = right_values.to_numpy()
assert_numpy_array_equal(
- left_values,
- right_values,
+ lv,
+ rv,
check_dtype=check_dtype,
obj=str(obj),
index_values=left.index,
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index aaf49f53ba02b..e38144f4c615b 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -421,16 +421,6 @@ def test_index_from_listlike_with_dtype(self, data):
def test_EA_types(self, engine, data, request):
super().test_EA_types(engine, data, request)
- @pytest.mark.xfail(reason="Expect NumpyEA, get np.ndarray")
- def test_compare_array(self, data, comparison_op):
- super().test_compare_array(data, comparison_op)
-
- def test_compare_scalar(self, data, comparison_op, request):
- if data.dtype.kind == "f" or comparison_op.__name__ in ["eq", "ne"]:
- mark = pytest.mark.xfail(reason="Expect NumpyEA, get np.ndarray")
- request.applymarker(mark)
- super().test_compare_scalar(data, comparison_op)
-
class Test2DCompat(base.NDArrayBacked2DTests):
pass
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index a074898f6046d..79132591b15b3 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -211,10 +211,7 @@ def test_assert_frame_equal_extension_dtype_mismatch():
"\\[right\\]: int[32|64]"
)
- # TODO: this shouldn't raise (or should raise a better error message)
- # https://github.com/pandas-dev/pandas/issues/56131
- with pytest.raises(AssertionError, match="classes are different"):
- tm.assert_frame_equal(left, right, check_dtype=False)
+ tm.assert_frame_equal(left, right, check_dtype=False)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(left, right, check_dtype=True)
@@ -246,7 +243,6 @@ def test_assert_frame_equal_ignore_extension_dtype_mismatch():
tm.assert_frame_equal(left, right, check_dtype=False)
-@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131")
def test_assert_frame_equal_ignore_extension_dtype_mismatch_cross_class():
# https://github.com/pandas-dev/pandas/issues/35715
left = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
@@ -300,9 +296,7 @@ def test_frame_equal_mixed_dtypes(frame_or_series, any_numeric_ea_dtype, indexer
dtypes = (any_numeric_ea_dtype, "int64")
obj1 = frame_or_series([1, 2], dtype=dtypes[indexer[0]])
obj2 = frame_or_series([1, 2], dtype=dtypes[indexer[1]])
- msg = r'(Series|DataFrame.iloc\[:, 0\] \(column name="0"\) classes) are different'
- with pytest.raises(AssertionError, match=msg):
- tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
+ tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
def test_assert_frame_equal_check_like_different_indexes():
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index f722f619bc456..c4ffc197298f0 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -290,10 +290,7 @@ def test_assert_series_equal_extension_dtype_mismatch():
\\[left\\]: Int64
\\[right\\]: int[32|64]"""
- # TODO: this shouldn't raise (or should raise a better error message)
- # https://github.com/pandas-dev/pandas/issues/56131
- with pytest.raises(AssertionError, match="Series classes are different"):
- tm.assert_series_equal(left, right, check_dtype=False)
+ tm.assert_series_equal(left, right, check_dtype=False)
with pytest.raises(AssertionError, match=msg):
tm.assert_series_equal(left, right, check_dtype=True)
@@ -372,7 +369,6 @@ def test_assert_series_equal_ignore_extension_dtype_mismatch():
tm.assert_series_equal(left, right, check_dtype=False)
-@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131")
def test_assert_series_equal_ignore_extension_dtype_mismatch_cross_class():
# https://github.com/pandas-dev/pandas/issues/35715
left = Series([1, 2, 3], dtype="Int64")
@@ -456,3 +452,13 @@ def test_large_unequal_ints(dtype):
right = Series([1577840521123543], dtype=dtype)
with pytest.raises(AssertionError, match="Series are different"):
tm.assert_series_equal(left, right)
+
+
+@pytest.mark.parametrize("dtype", [None, object])
+@pytest.mark.parametrize("check_exact", [True, False])
+@pytest.mark.parametrize("val", [3, 3.5])
+def test_ea_and_numpy_no_dtype_check(val, check_exact, dtype):
+ # GH#56651
+ left = Series([1, 2, val], dtype=dtype)
+ right = Series(pd.array([1, 2, val]))
+ tm.assert_series_equal(left, right, check_dtype=False, check_exact=check_exact)
| Backport PR #56654: BUG: assert_series_equal not properly respecting check-dtype | https://api.github.com/repos/pandas-dev/pandas/pulls/56668 | 2023-12-28T21:44:11Z | 2023-12-28T22:17:15Z | 2023-12-28T22:17:15Z | 2023-12-28T22:17:15Z |
TYP: misc annotations | diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py
index f11dc11f6ac0d..f9cf390ba59de 100644
--- a/pandas/_testing/_warnings.py
+++ b/pandas/_testing/_warnings.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from contextlib import (
+ AbstractContextManager,
contextmanager,
nullcontext,
)
@@ -112,7 +113,9 @@ class for all warnings. To raise multiple types of exceptions,
)
-def maybe_produces_warning(warning: type[Warning], condition: bool, **kwargs):
+def maybe_produces_warning(
+ warning: type[Warning], condition: bool, **kwargs
+) -> AbstractContextManager:
"""
Return a context manager that possibly checks a warning based on the condition
"""
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 9d04d7c0a1216..3cdeae52a25ba 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -2,7 +2,11 @@
import importlib
import sys
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ Literal,
+ overload,
+)
import warnings
from pandas.util._exceptions import find_stack_level
@@ -82,12 +86,35 @@ def get_version(module: types.ModuleType) -> str:
return version
+@overload
+def import_optional_dependency(
+ name: str,
+ extra: str = ...,
+ min_version: str | None = ...,
+ *,
+ errors: Literal["raise"] = ...,
+) -> types.ModuleType:
+ ...
+
+
+@overload
+def import_optional_dependency(
+ name: str,
+ extra: str = ...,
+ min_version: str | None = ...,
+ *,
+ errors: Literal["warn", "ignore"],
+) -> types.ModuleType | None:
+ ...
+
+
def import_optional_dependency(
name: str,
extra: str = "",
- errors: str = "raise",
min_version: str | None = None,
-):
+ *,
+ errors: Literal["raise", "warn", "ignore"] = "raise",
+) -> types.ModuleType | None:
"""
Import an optional dependency.
diff --git a/pandas/core/arrays/_arrow_string_mixins.py b/pandas/core/arrays/_arrow_string_mixins.py
index cc41985843574..bfff19a123a08 100644
--- a/pandas/core/arrays/_arrow_string_mixins.py
+++ b/pandas/core/arrays/_arrow_string_mixins.py
@@ -1,6 +1,9 @@
from __future__ import annotations
-from typing import Literal
+from typing import (
+ TYPE_CHECKING,
+ Literal,
+)
import numpy as np
@@ -10,6 +13,9 @@
import pyarrow as pa
import pyarrow.compute as pc
+if TYPE_CHECKING:
+ from pandas._typing import Self
+
class ArrowStringArrayMixin:
_pa_array = None
@@ -22,7 +28,7 @@ def _str_pad(
width: int,
side: Literal["left", "right", "both"] = "left",
fillchar: str = " ",
- ):
+ ) -> Self:
if side == "left":
pa_pad = pc.utf8_lpad
elif side == "right":
@@ -35,7 +41,7 @@ def _str_pad(
)
return type(self)(pa_pad(self._pa_array, width=width, padding=fillchar))
- def _str_get(self, i: int):
+ def _str_get(self, i: int) -> Self:
lengths = pc.utf8_length(self._pa_array)
if i >= 0:
out_of_bounds = pc.greater_equal(i, lengths)
@@ -59,7 +65,7 @@ def _str_get(self, i: int):
def _str_slice_replace(
self, start: int | None = None, stop: int | None = None, repl: str | None = None
- ):
+ ) -> Self:
if repl is None:
repl = ""
if start is None:
@@ -68,13 +74,13 @@ def _str_slice_replace(
stop = np.iinfo(np.int64).max
return type(self)(pc.utf8_replace_slice(self._pa_array, start, stop, repl))
- def _str_capitalize(self):
+ def _str_capitalize(self) -> Self:
return type(self)(pc.utf8_capitalize(self._pa_array))
- def _str_title(self):
+ def _str_title(self) -> Self:
return type(self)(pc.utf8_title(self._pa_array))
- def _str_swapcase(self):
+ def _str_swapcase(self) -> Self:
return type(self)(pc.utf8_swapcase(self._pa_array))
def _str_removesuffix(self, suffix: str):
diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py
index f551716772f61..e87b7f02b9b05 100644
--- a/pandas/core/dtypes/inference.py
+++ b/pandas/core/dtypes/inference.py
@@ -36,7 +36,7 @@
is_iterator = lib.is_iterator
-def is_number(obj) -> TypeGuard[Number | np.number]:
+def is_number(obj: object) -> TypeGuard[Number | np.number]:
"""
Check if the object is a number.
@@ -77,7 +77,7 @@ def is_number(obj) -> TypeGuard[Number | np.number]:
return isinstance(obj, (Number, np.number))
-def iterable_not_string(obj) -> bool:
+def iterable_not_string(obj: object) -> bool:
"""
Check if the object is an iterable but not a string.
@@ -102,7 +102,7 @@ def iterable_not_string(obj) -> bool:
return isinstance(obj, abc.Iterable) and not isinstance(obj, str)
-def is_file_like(obj) -> bool:
+def is_file_like(obj: object) -> bool:
"""
Check if the object is a file-like object.
@@ -138,7 +138,7 @@ def is_file_like(obj) -> bool:
return bool(hasattr(obj, "__iter__"))
-def is_re(obj) -> TypeGuard[Pattern]:
+def is_re(obj: object) -> TypeGuard[Pattern]:
"""
Check if the object is a regex pattern instance.
@@ -163,7 +163,7 @@ def is_re(obj) -> TypeGuard[Pattern]:
return isinstance(obj, Pattern)
-def is_re_compilable(obj) -> bool:
+def is_re_compilable(obj: object) -> bool:
"""
Check if the object can be compiled into a regex pattern instance.
@@ -185,14 +185,14 @@ def is_re_compilable(obj) -> bool:
False
"""
try:
- re.compile(obj)
+ re.compile(obj) # type: ignore[call-overload]
except TypeError:
return False
else:
return True
-def is_array_like(obj) -> bool:
+def is_array_like(obj: object) -> bool:
"""
Check if the object is array-like.
@@ -224,7 +224,7 @@ def is_array_like(obj) -> bool:
return is_list_like(obj) and hasattr(obj, "dtype")
-def is_nested_list_like(obj) -> bool:
+def is_nested_list_like(obj: object) -> bool:
"""
Check if the object is list-like, and that all of its elements
are also list-like.
@@ -265,12 +265,13 @@ def is_nested_list_like(obj) -> bool:
return (
is_list_like(obj)
and hasattr(obj, "__len__")
- and len(obj) > 0
- and all(is_list_like(item) for item in obj)
+ # need PEP 724 to handle these typing errors
+ and len(obj) > 0 # pyright: ignore[reportGeneralTypeIssues]
+ and all(is_list_like(item) for item in obj) # type: ignore[attr-defined]
)
-def is_dict_like(obj) -> bool:
+def is_dict_like(obj: object) -> bool:
"""
Check if the object is dict-like.
@@ -303,7 +304,7 @@ def is_dict_like(obj) -> bool:
)
-def is_named_tuple(obj) -> bool:
+def is_named_tuple(obj: object) -> bool:
"""
Check if the object is a named tuple.
@@ -331,7 +332,7 @@ def is_named_tuple(obj) -> bool:
return isinstance(obj, abc.Sequence) and hasattr(obj, "_fields")
-def is_hashable(obj) -> TypeGuard[Hashable]:
+def is_hashable(obj: object) -> TypeGuard[Hashable]:
"""
Return True if hash(obj) will succeed, False otherwise.
@@ -370,7 +371,7 @@ def is_hashable(obj) -> TypeGuard[Hashable]:
return True
-def is_sequence(obj) -> bool:
+def is_sequence(obj: object) -> bool:
"""
Check if the object is a sequence of objects.
String types are not included as sequences here.
@@ -394,14 +395,16 @@ def is_sequence(obj) -> bool:
False
"""
try:
- iter(obj) # Can iterate over it.
- len(obj) # Has a length associated with it.
+ # Can iterate over it.
+ iter(obj) # type: ignore[call-overload]
+ # Has a length associated with it.
+ len(obj) # type: ignore[arg-type]
return not isinstance(obj, (str, bytes))
except (TypeError, AttributeError):
return False
-def is_dataclass(item) -> bool:
+def is_dataclass(item: object) -> bool:
"""
Checks if the object is a data-class instance
diff --git a/pandas/core/flags.py b/pandas/core/flags.py
index aff7a15f283ba..394695e69a3d3 100644
--- a/pandas/core/flags.py
+++ b/pandas/core/flags.py
@@ -111,7 +111,7 @@ def __setitem__(self, key: str, value) -> None:
def __repr__(self) -> str:
return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"
- def __eq__(self, other) -> bool:
+ def __eq__(self, other: object) -> bool:
if isinstance(other, type(self)):
return self.allows_duplicate_labels == other.allows_duplicate_labels
return False
diff --git a/pandas/core/ops/invalid.py b/pandas/core/ops/invalid.py
index e5ae6d359ac22..8af95de285938 100644
--- a/pandas/core/ops/invalid.py
+++ b/pandas/core/ops/invalid.py
@@ -4,7 +4,11 @@
from __future__ import annotations
import operator
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ NoReturn,
+)
import numpy as np
@@ -41,7 +45,7 @@ def invalid_comparison(left, right, op) -> npt.NDArray[np.bool_]:
return res_values
-def make_invalid_op(name: str):
+def make_invalid_op(name: str) -> Callable[..., NoReturn]:
"""
Return a binary method that always raises a TypeError.
@@ -54,7 +58,7 @@ def make_invalid_op(name: str):
invalid_op : function
"""
- def invalid_op(self, other=None):
+ def invalid_op(self, other=None) -> NoReturn:
typ = type(self).__name__
raise TypeError(f"cannot perform {name} with this index type: {typ}")
diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py
index fc685935a35fc..fb5980184355c 100644
--- a/pandas/core/ops/missing.py
+++ b/pandas/core/ops/missing.py
@@ -30,7 +30,7 @@
from pandas.core import roperator
-def _fill_zeros(result: np.ndarray, x, y):
+def _fill_zeros(result: np.ndarray, x, y) -> np.ndarray:
"""
If this is a reversed op, then flip x,y
diff --git a/pandas/io/orc.py b/pandas/io/orc.py
index fed9463c38d5d..ed9bc21075e73 100644
--- a/pandas/io/orc.py
+++ b/pandas/io/orc.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import io
-from types import ModuleType
from typing import (
TYPE_CHECKING,
Any,
@@ -218,7 +217,7 @@ def to_orc(
if engine != "pyarrow":
raise ValueError("engine must be 'pyarrow'")
- engine = import_optional_dependency(engine, min_version="10.0.1")
+ pyarrow = import_optional_dependency(engine, min_version="10.0.1")
pa = import_optional_dependency("pyarrow")
orc = import_optional_dependency("pyarrow.orc")
@@ -227,10 +226,9 @@ def to_orc(
path = io.BytesIO()
assert path is not None # For mypy
with get_handle(path, "wb", is_text=False) as handles:
- assert isinstance(engine, ModuleType) # For mypy
try:
orc.write_table(
- engine.Table.from_pandas(df, preserve_index=index),
+ pyarrow.Table.from_pandas(df, preserve_index=index),
handles.handle,
**engine_kwargs,
)
diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py
index 82b3aa56c653c..91282fde8b11d 100644
--- a/pandas/util/__init__.py
+++ b/pandas/util/__init__.py
@@ -25,5 +25,5 @@ def __getattr__(key: str):
raise AttributeError(f"module 'pandas.util' has no attribute '{key}'")
-def capitalize_first_letter(s):
+def capitalize_first_letter(s: str) -> str:
return s[:1].upper() + s[1:]
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index 4e8189e72c427..aef91064d12fb 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -340,7 +340,7 @@ def wrapper(*args, **kwargs):
return decorate
-def doc(*docstrings: None | str | Callable, **params) -> Callable[[F], F]:
+def doc(*docstrings: None | str | Callable, **params: object) -> Callable[[F], F]:
"""
A decorator to take docstring templates, concatenate them and perform string
substitution on them.
diff --git a/pyproject.toml b/pyproject.toml
index 5e65edf81f9c7..430bb8e505df0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -583,7 +583,6 @@ module = [
"pandas._testing.*", # TODO
"pandas.arrays", # TODO
"pandas.compat.numpy.function", # TODO
- "pandas.compat._optional", # TODO
"pandas.compat.compressors", # TODO
"pandas.compat.pickle_compat", # TODO
"pandas.core._numba.executor", # TODO
@@ -602,7 +601,6 @@ module = [
"pandas.core.dtypes.concat", # TODO
"pandas.core.dtypes.dtypes", # TODO
"pandas.core.dtypes.generic", # TODO
- "pandas.core.dtypes.inference", # TODO
"pandas.core.dtypes.missing", # TODO
"pandas.core.groupby.categorical", # TODO
"pandas.core.groupby.generic", # TODO
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56667 | 2023-12-28T21:08:14Z | 2023-12-29T00:41:42Z | 2023-12-29T00:41:42Z | 2024-01-17T02:49:48Z |
STY: Use ruff instead of pygrep check for future annotation import | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7f3fc95ce00cc..4b02ad7cf886f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -358,18 +358,6 @@ repos:
files: ^pandas/
exclude: ^(pandas/_libs/|pandas/tests/|pandas/errors/__init__.py$|pandas/_version.py)
types: [python]
- - id: future-annotations
- name: import annotations from __future__
- entry: 'from __future__ import annotations'
- language: pygrep
- args: [--negate]
- files: ^pandas/
- types: [python]
- exclude: |
- (?x)
- /(__init__\.py)|(api\.py)|(_version\.py)|(testing\.py)|(conftest\.py)$
- |/tests/
- |/_testing/
- id: check-test-naming
name: check that test names start with 'test'
entry: python -m scripts.check_test_naming
diff --git a/pyproject.toml b/pyproject.toml
index 5e65edf81f9c7..8724a25909543 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -259,6 +259,8 @@ select = [
"FLY",
# flake8-logging-format
"G",
+ # flake8-future-annotations
+ "FA",
]
ignore = [
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56666 | 2023-12-28T20:05:38Z | 2023-12-29T21:53:09Z | 2023-12-29T21:53:09Z | 2023-12-29T22:58:39Z |
Backport PR #56370 on branch 2.2.x (BUG: rolling with datetime ArrowDtype) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 1da18cd9be8f9..129f5cedb86c2 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -865,6 +865,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.resample` when resampling on a :class:`ArrowDtype` of ``pyarrow.timestamp`` or ``pyarrow.duration`` type (:issue:`55989`)
- Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55281`)
- Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.MonthBegin` (:issue:`55271`)
+- Bug in :meth:`DataFrame.rolling` and :meth:`Series.rolling` where either the ``index`` or ``on`` column was :class:`ArrowDtype` with ``pyarrow.timestamp`` type (:issue:`55849`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 11a0c7bf18fcb..a0e0a1434e871 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -92,6 +92,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
CategoricalDtype,
DatetimeTZDtype,
ExtensionDtype,
@@ -2531,7 +2532,7 @@ def _validate_inferred_freq(
return freq
-def dtype_to_unit(dtype: DatetimeTZDtype | np.dtype) -> str:
+def dtype_to_unit(dtype: DatetimeTZDtype | np.dtype | ArrowDtype) -> str:
"""
Return the unit str corresponding to the dtype's resolution.
@@ -2546,4 +2547,8 @@ def dtype_to_unit(dtype: DatetimeTZDtype | np.dtype) -> str:
"""
if isinstance(dtype, DatetimeTZDtype):
return dtype.unit
+ elif isinstance(dtype, ArrowDtype):
+ if dtype.kind not in "mM":
+ raise ValueError(f"{dtype=} does not have a resolution.")
+ return dtype.pyarrow_dtype.unit
return np.datetime_data(dtype)[0]
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index e78bd258c11ff..68cec16ec9eca 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -14,7 +14,6 @@
Any,
Callable,
Literal,
- cast,
)
import numpy as np
@@ -39,6 +38,7 @@
is_numeric_dtype,
needs_i8_conversion,
)
+from pandas.core.dtypes.dtypes import ArrowDtype
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCSeries,
@@ -104,6 +104,7 @@
NDFrameT,
QuantileInterpolation,
WindowingRankType,
+ npt,
)
from pandas import (
@@ -404,11 +405,12 @@ def _insert_on_column(self, result: DataFrame, obj: DataFrame) -> None:
result[name] = extra_col
@property
- def _index_array(self):
+ def _index_array(self) -> npt.NDArray[np.int64] | None:
# TODO: why do we get here with e.g. MultiIndex?
- if needs_i8_conversion(self._on.dtype):
- idx = cast("PeriodIndex | DatetimeIndex | TimedeltaIndex", self._on)
- return idx.asi8
+ if isinstance(self._on, (PeriodIndex, DatetimeIndex, TimedeltaIndex)):
+ return self._on.asi8
+ elif isinstance(self._on.dtype, ArrowDtype) and self._on.dtype.kind in "mM":
+ return self._on.to_numpy(dtype=np.int64)
return None
def _resolve_output(self, out: DataFrame, obj: DataFrame) -> DataFrame:
@@ -439,7 +441,7 @@ def _apply_series(
self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None
) -> Series:
"""
- Series version of _apply_blockwise
+ Series version of _apply_columnwise
"""
obj = self._create_data(self._selected_obj)
@@ -455,7 +457,7 @@ def _apply_series(
index = self._slice_axis_for_step(obj.index, result)
return obj._constructor(result, index=index, name=obj.name)
- def _apply_blockwise(
+ def _apply_columnwise(
self,
homogeneous_func: Callable[..., ArrayLike],
name: str,
@@ -614,7 +616,7 @@ def calc(x):
return result
if self.method == "single":
- return self._apply_blockwise(homogeneous_func, name, numeric_only)
+ return self._apply_columnwise(homogeneous_func, name, numeric_only)
else:
return self._apply_tablewise(homogeneous_func, name, numeric_only)
@@ -1232,7 +1234,9 @@ def calc(x):
return result
- return self._apply_blockwise(homogeneous_func, name, numeric_only)[:: self.step]
+ return self._apply_columnwise(homogeneous_func, name, numeric_only)[
+ :: self.step
+ ]
@doc(
_shared_docs["aggregate"],
@@ -1868,6 +1872,7 @@ def _validate(self):
if (
self.obj.empty
or isinstance(self._on, (DatetimeIndex, TimedeltaIndex, PeriodIndex))
+ or (isinstance(self._on.dtype, ArrowDtype) and self._on.dtype.kind in "mM")
) and isinstance(self.window, (str, BaseOffset, timedelta)):
self._validate_datetimelike_monotonic()
diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py
index c99fc8a8eb60f..bd0fadeb3e475 100644
--- a/pandas/tests/window/test_timeseries_window.py
+++ b/pandas/tests/window/test_timeseries_window.py
@@ -1,9 +1,12 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
from pandas import (
DataFrame,
DatetimeIndex,
+ Index,
MultiIndex,
NaT,
Series,
@@ -697,3 +700,16 @@ def test_nat_axis_error(msg, axis):
with pytest.raises(ValueError, match=f"{msg} values must not have NaT"):
with tm.assert_produces_warning(FutureWarning, match=warn_msg):
df.rolling("D", axis=axis).mean()
+
+
+@td.skip_if_no("pyarrow")
+def test_arrow_datetime_axis():
+ # GH 55849
+ expected = Series(
+ np.arange(5, dtype=np.float64),
+ index=Index(
+ date_range("2020-01-01", periods=5), dtype="timestamp[ns][pyarrow]"
+ ),
+ )
+ result = expected.rolling("1D").sum()
+ tm.assert_series_equal(result, expected)
| Backport PR #56370: BUG: rolling with datetime ArrowDtype | https://api.github.com/repos/pandas-dev/pandas/pulls/56665 | 2023-12-28T19:32:08Z | 2023-12-28T21:44:56Z | 2023-12-28T21:44:56Z | 2023-12-28T21:44:56Z |
CI: Run jobs on 2.2.x branch | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index b49b9a67c4743..8e29d56f47dcf 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index da232404e6ff5..73acd9acc129a 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -4,13 +4,13 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
tags:
- '*'
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml
index 04d8b8e006985..d59ddf272f705 100644
--- a/.github/workflows/package-checks.yml
+++ b/.github/workflows/package-checks.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
types: [ labeled, opened, synchronize, reopened ]
permissions:
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 6ca4d19196874..12e645dc9da81 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- - 2.1.x
+ - 2.2.x
pull_request:
branches:
- main
- - 2.1.x
+ - 2.2.x
paths-ignore:
- "doc/**"
- "web/**"
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56664 | 2023-12-28T19:27:52Z | 2023-12-28T21:45:17Z | 2023-12-28T21:45:17Z | 2023-12-28T22:28:08Z |
Pyarrow stringmatch fix | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b1164301e6d79..14acbae2b1f4e 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -2277,7 +2277,7 @@ def _str_match(
def _str_fullmatch(
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
):
- if not pat.endswith("$") or pat.endswith("//$"):
+ if not pat.endswith("$") or pat.endswith("\$"):
pat = f"{pat}$"
return self._str_match(pat, case, flags, na)
| closes #56652
Added the change for partial string matching. | https://api.github.com/repos/pandas-dev/pandas/pulls/56663 | 2023-12-28T19:06:14Z | 2024-01-03T18:41:53Z | null | 2024-01-03T18:41:53Z |
Backport PR #56641 on branch 2.2.x (DOC: Add optional dependencies table in 2.2 whatsnew) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index d60dbefd83195..2ad5717bc0320 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -417,15 +417,63 @@ Backwards incompatible API changes
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
-The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
-Optional libraries below the lowest tested version may still work, but are not considered supported.
-
-+-----------------+-----------------+---------+
-| Package | Minimum Version | Changed |
-+=================+=================+=========+
-| mypy (dev) | 1.8.0 | X |
-+-----------------+-----------------+---------+
+For `optional dependencies <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
+Optional dependencies below the lowest tested version may still work but are not considered supported.
+The following table lists the optional dependencies that have had their minimum tested version increased.
+
++-----------------+---------------------+
+| Package | New Minimum Version |
++=================+=====================+
+| beautifulsoup4 | 4.11.2 |
++-----------------+---------------------+
+| blosc | 1.21.3 |
++-----------------+---------------------+
+| bottleneck | 1.3.6 |
++-----------------+---------------------+
+| fastparquet | 2022.12.0 |
++-----------------+---------------------+
+| fsspec | 2022.11.0 |
++-----------------+---------------------+
+| gcsfs | 2022.11.0 |
++-----------------+---------------------+
+| lxml | 4.9.2 |
++-----------------+---------------------+
+| matplotlib | 3.6.3 |
++-----------------+---------------------+
+| numba | 0.56.4 |
++-----------------+---------------------+
+| numexpr | 2.8.4 |
++-----------------+---------------------+
+| qtpy | 2.3.0 |
++-----------------+---------------------+
+| openpyxl | 3.1.0 |
++-----------------+---------------------+
+| psycopg2 | 2.9.6 |
++-----------------+---------------------+
+| pyreadstat | 1.2.0 |
++-----------------+---------------------+
+| pytables | 3.8.0 |
++-----------------+---------------------+
+| pyxlsb | 1.0.10 |
++-----------------+---------------------+
+| s3fs | 2022.11.0 |
++-----------------+---------------------+
+| scipy | 1.10.0 |
++-----------------+---------------------+
+| sqlalchemy | 2.0.0 |
++-----------------+---------------------+
+| tabulate | 0.9.0 |
++-----------------+---------------------+
+| xarray | 2022.12.0 |
++-----------------+---------------------+
+| xlsxwriter | 3.0.5 |
++-----------------+---------------------+
+| zstandard | 0.19.0 |
++-----------------+---------------------+
+| pyqt5 | 5.15.8 |
++-----------------+---------------------+
+| tzdata | 2022.7 |
++-----------------+---------------------+
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
| Backport PR #56641: DOC: Add optional dependencies table in 2.2 whatsnew | https://api.github.com/repos/pandas-dev/pandas/pulls/56662 | 2023-12-28T19:04:00Z | 2023-12-28T19:23:31Z | 2023-12-28T19:23:31Z | 2023-12-28T19:23:31Z |
added instance check for the periods argument | diff --git a/pandas/core/series.py b/pandas/core/series.py
index e3b401cd3c88b..0080eb13f1703 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3102,6 +3102,9 @@ def diff(self, periods: int = 1) -> Series:
--------
{examples}
"""
+ if not isinstance(periods, int):
+ raise ValueError("periods must be an integer")
+
result = algorithms.diff(self._values, periods)
return self._constructor(result, index=self.index, copy=False).__finalize__(
self, method="diff"
| This Pull Request addresses the issue #56607,
Changes Made:
- added a simple instance check before algorithms.diff()
Screenshot after change
<img width="374" alt="image" src="https://github.com/pandas-dev/pandas/assets/34889400/8e18821b-4a8d-4067-9357-03dc187bea15">
| https://api.github.com/repos/pandas-dev/pandas/pulls/56661 | 2023-12-28T18:57:14Z | 2024-01-01T00:41:49Z | null | 2024-01-01T00:41:49Z |
Backport PR #56635 on branch 2.2.x (CoW: Boolean indexer in MultiIndex raising read-only error) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 34c9c142d3870..cbce6717fef51 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -761,6 +761,7 @@ Interval
Indexing
^^^^^^^^
+- Bug in :meth:`DataFrame.loc` mutating a boolean indexer when :class:`DataFrame` has a :class:`MultiIndex` (:issue:`56635`)
- Bug in :meth:`DataFrame.loc` when setting :class:`Series` with extension dtype into NumPy dtype (:issue:`55604`)
- Bug in :meth:`Index.difference` not returning a unique set of values when ``other`` is empty or ``other`` is considered non-comparable (:issue:`55113`)
- Bug in setting :class:`Categorical` values into a :class:`DataFrame` with numpy dtypes raising ``RecursionError`` (:issue:`52927`)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 2a4e027e2b806..02a841a2075fd 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3488,6 +3488,8 @@ def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]:
"is not the same length as the index"
)
lvl_indexer = np.asarray(k)
+ if indexer is None:
+ lvl_indexer = lvl_indexer.copy()
elif is_list_like(k):
# a collection of labels to include from this level (these are or'd)
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py
index 6f3850ab64daa..2681c07f01990 100644
--- a/pandas/tests/copy_view/test_indexing.py
+++ b/pandas/tests/copy_view/test_indexing.py
@@ -1224,6 +1224,27 @@ def test_series_midx_tuples_slice(using_copy_on_write, warn_copy_on_write):
tm.assert_series_equal(ser, expected)
+def test_midx_read_only_bool_indexer():
+ # GH#56635
+ def mklbl(prefix, n):
+ return [f"{prefix}{i}" for i in range(n)]
+
+ idx = pd.MultiIndex.from_product(
+ [mklbl("A", 4), mklbl("B", 2), mklbl("C", 4), mklbl("D", 2)]
+ )
+ cols = pd.MultiIndex.from_tuples(
+ [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"]
+ )
+ df = DataFrame(1, index=idx, columns=cols).sort_index().sort_index(axis=1)
+
+ mask = df[("a", "foo")] == 1
+ expected_mask = mask.copy()
+ result = df.loc[pd.IndexSlice[mask, :, ["C1", "C3"]], :]
+ expected = df.loc[pd.IndexSlice[:, :, ["C1", "C3"]], :]
+ tm.assert_frame_equal(result, expected)
+ tm.assert_series_equal(mask, expected_mask)
+
+
def test_loc_enlarging_with_dataframe(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3]})
rhs = DataFrame({"b": [1, 2, 3], "c": [4, 5, 6]})
| Backport PR #56635: CoW: Boolean indexer in MultiIndex raising read-only error | https://api.github.com/repos/pandas-dev/pandas/pulls/56660 | 2023-12-28T18:48:32Z | 2023-12-28T19:22:59Z | 2023-12-28T19:22:59Z | 2023-12-28T19:22:59Z |
added validation for series datatypes | diff --git a/pandas/core/series.py b/pandas/core/series.py
index e3b401cd3c88b..6d47e52cd99a4 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -73,6 +73,7 @@
from pandas.core.dtypes.common import (
is_dict_like,
is_integer,
+ is_float,
is_iterator,
is_list_like,
is_object_dtype,
@@ -3102,6 +3103,10 @@ def diff(self, periods: int = 1) -> Series:
--------
{examples}
"""
+ if not lib.is_integer(periods):
+ if not (is_float(periods) and periods.is_integer()):
+ raise ValueError("periods must be an integer")
+ periods = int(periods)
result = algorithms.diff(self._values, periods)
return self._constructor(result, index=self.index, copy=False).__finalize__(
self, method="diff"
| closes #56607
This fix makes sure Series.diff validates and throws an exception based on the datatype.
Changes made:
- import "is_float" from pandas
- Checking if the input periods are integers/float or not before calling "algorithms.diff"
Behaviour after the changes:
<img width="480" alt="image" src="https://github.com/pandas-dev/pandas/assets/26180886/4f52a26e-11c3-4c24-b07b-168381ee171e">
| https://api.github.com/repos/pandas-dev/pandas/pulls/56659 | 2023-12-28T18:48:06Z | 2024-01-01T00:41:59Z | null | 2024-01-01T00:41:59Z |
Backport PR #56613 on branch 2.2.x (BUG: Added raising when merging datetime columns with timedelta columns) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 34c9c142d3870..d60dbefd83195 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -824,6 +824,7 @@ Reshaping
- Bug in :func:`merge_asof` raising ``TypeError`` when ``by`` dtype is not ``object``, ``int64``, or ``uint64`` (:issue:`22794`)
- Bug in :func:`merge_asof` raising incorrect error for string dtype (:issue:`56444`)
- Bug in :func:`merge_asof` when using a :class:`Timedelta` tolerance on a :class:`ArrowDtype` column (:issue:`56486`)
+- Bug in :func:`merge` not raising when merging datetime columns with timedelta columns (:issue:`56455`)
- Bug in :func:`merge` not raising when merging string columns with numeric columns (:issue:`56441`)
- Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`)
- Bug in :meth:`DataFrame.melt` where an exception was raised if ``var_name`` was not a string (:issue:`55948`)
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 690e3c2700c6c..320e4e33a29fb 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -1526,6 +1526,11 @@ def _maybe_coerce_merge_keys(self) -> None:
) or (lk.dtype.kind == "M" and rk.dtype.kind == "M"):
# allows datetime with different resolutions
continue
+ # datetime and timedelta not allowed
+ elif lk.dtype.kind == "M" and rk.dtype.kind == "m":
+ raise ValueError(msg)
+ elif lk.dtype.kind == "m" and rk.dtype.kind == "M":
+ raise ValueError(msg)
elif is_object_dtype(lk.dtype) and is_object_dtype(rk.dtype):
continue
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index d7a343ae9f152..ab8d22e567d27 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2988,3 +2988,23 @@ def test_merge_empty_frames_column_order(left_empty, right_empty):
elif right_empty:
expected.loc[:, ["C", "D"]] = np.nan
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("how", ["left", "right", "inner", "outer"])
+def test_merge_datetime_and_timedelta(how):
+ left = DataFrame({"key": Series([1, None], dtype="datetime64[ns]")})
+ right = DataFrame({"key": Series([1], dtype="timedelta64[ns]")})
+
+ msg = (
+ f"You are trying to merge on {left['key'].dtype} and {right['key'].dtype} "
+ "columns for key 'key'. If you wish to proceed you should use pd.concat"
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ left.merge(right, on="key", how=how)
+
+ msg = (
+ f"You are trying to merge on {right['key'].dtype} and {left['key'].dtype} "
+ "columns for key 'key'. If you wish to proceed you should use pd.concat"
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ right.merge(left, on="key", how=how)
| Backport PR #56613: BUG: Added raising when merging datetime columns with timedelta columns | https://api.github.com/repos/pandas-dev/pandas/pulls/56658 | 2023-12-28T17:33:33Z | 2023-12-28T18:52:44Z | 2023-12-28T18:52:44Z | 2023-12-28T18:52:44Z |
testing | diff --git a/README.md b/README.md
index 6fa20d237babe..d7a95825c143b 100644
--- a/README.md
+++ b/README.md
@@ -4,8 +4,7 @@
-----------------
-# pandas: powerful Python data analysis toolkit
-
+# pandas: Unlock the full potential of data analysis with the most powerful and flexible open-source Python toolkit.
| | |
| --- | --- |
| Testing | [](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [](https://codecov.io/gh/pandas-dev/pandas) |
| Just For Testing please consider it. | https://api.github.com/repos/pandas-dev/pandas/pulls/56657 | 2023-12-28T16:12:49Z | 2023-12-28T16:16:18Z | null | 2023-12-28T16:16:19Z |
Backport PR #56650 on branch 2.2.x (ENH: Implement dt methods for pyarrow duration types) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..f7e1cc9cbe36d 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -316,6 +316,7 @@ Other enhancements
- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
+- Implemented :meth:`Series.dt` methods and attributes for :class:`ArrowDtype` with ``pyarrow.duration`` type (:issue:`52284`)
- Implemented :meth:`Series.str.extract` for :class:`ArrowDtype` (:issue:`56268`)
- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as ``"BMS"`` (:issue:`56243`)
- Improved error message when constructing :class:`Period` with invalid offsets such as ``"QS"`` (:issue:`55785`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index de1ed9ecfdaf1..32a4cadff8270 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -17,6 +17,7 @@
from pandas._libs import lib
from pandas._libs.tslibs import (
+ NaT,
Timedelta,
Timestamp,
timezones,
@@ -2498,6 +2499,92 @@ def _str_wrap(self, width: int, **kwargs):
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
+ @property
+ def _dt_days(self):
+ return type(self)(
+ pa.array(self._to_timedeltaarray().days, from_pandas=True, type=pa.int32())
+ )
+
+ @property
+ def _dt_hours(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.hours if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_minutes(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.minutes if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_seconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().seconds, from_pandas=True, type=pa.int32()
+ )
+ )
+
+ @property
+ def _dt_milliseconds(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.milliseconds if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_microseconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().microseconds,
+ from_pandas=True,
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_nanoseconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().nanoseconds, from_pandas=True, type=pa.int32()
+ )
+ )
+
+ def _dt_to_pytimedelta(self):
+ data = self._pa_array.to_pylist()
+ if self._dtype.pyarrow_dtype.unit == "ns":
+ data = [None if ts is None else ts.to_pytimedelta() for ts in data]
+ return np.array(data, dtype=object)
+
+ def _dt_total_seconds(self):
+ return type(self)(
+ pa.array(self._to_timedeltaarray().total_seconds(), from_pandas=True)
+ )
+
+ def _dt_as_unit(self, unit: str):
+ if pa.types.is_date(self.dtype.pyarrow_dtype):
+ raise NotImplementedError("as_unit not implemented for date types")
+ pd_array = self._maybe_convert_datelike_array()
+ # Don't just cast _pa_array in order to follow pandas unit conversion rules
+ return type(self)(pa.array(pd_array.as_unit(unit), from_pandas=True))
+
@property
def _dt_year(self):
return type(self)(pc.year(self._pa_array))
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 929c7f4a63f8f..7e3ba4089ff60 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -148,6 +148,20 @@ def _delegate_method(self, name: str, *args, **kwargs):
return result
+@delegate_names(
+ delegate=ArrowExtensionArray,
+ accessors=TimedeltaArray._datetimelike_ops,
+ typ="property",
+ accessor_mapping=lambda x: f"_dt_{x}",
+ raise_on_missing=False,
+)
+@delegate_names(
+ delegate=ArrowExtensionArray,
+ accessors=TimedeltaArray._datetimelike_methods,
+ typ="method",
+ accessor_mapping=lambda x: f"_dt_{x}",
+ raise_on_missing=False,
+)
@delegate_names(
delegate=ArrowExtensionArray,
accessors=DatetimeArray._datetimelike_ops,
@@ -213,6 +227,9 @@ def _delegate_method(self, name: str, *args, **kwargs):
return result
+ def to_pytimedelta(self):
+ return cast(ArrowExtensionArray, self._parent.array)._dt_to_pytimedelta()
+
def to_pydatetime(self):
# GH#20306
warnings.warn(
@@ -241,6 +258,26 @@ def isocalendar(self) -> DataFrame:
)
return iso_calendar_df
+ @property
+ def components(self) -> DataFrame:
+ from pandas import DataFrame
+
+ components_df = DataFrame(
+ {
+ col: getattr(self._parent.array, f"_dt_{col}")
+ for col in [
+ "days",
+ "hours",
+ "minutes",
+ "seconds",
+ "milliseconds",
+ "microseconds",
+ "nanoseconds",
+ ]
+ }
+ )
+ return components_df
+
@delegate_names(
delegate=DatetimeArray,
@@ -592,7 +629,7 @@ def __new__(cls, data: Series): # pyright: ignore[reportInconsistentConstructor
index=orig.index,
)
- if isinstance(data.dtype, ArrowDtype) and data.dtype.kind == "M":
+ if isinstance(data.dtype, ArrowDtype) and data.dtype.kind in "Mm":
return ArrowTemporalProperties(data, orig)
if lib.is_np_dtype(data.dtype, "M"):
return DatetimeProperties(data, orig)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 5624acfb64764..20cdcb9ce9ab8 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -2723,6 +2723,111 @@ def test_dt_tz_convert(unit):
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("dtype", ["timestamp[ms][pyarrow]", "duration[ms][pyarrow]"])
+def test_as_unit(dtype):
+ # GH 52284
+ ser = pd.Series([1000, None], dtype=dtype)
+ result = ser.dt.as_unit("ns")
+ expected = ser.astype(dtype.replace("ms", "ns"))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "prop, expected",
+ [
+ ["days", 1],
+ ["seconds", 2],
+ ["microseconds", 3],
+ ["nanoseconds", 4],
+ ],
+)
+def test_dt_timedelta_properties(prop, expected):
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = getattr(ser.dt, prop)
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([expected, None], type=pa.int32()))
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_timedelta_total_seconds():
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = ser.dt.total_seconds()
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([86402.000003, None], type=pa.float64()))
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_to_pytimedelta():
+ # GH 52284
+ data = [timedelta(1, 2, 3), timedelta(1, 2, 4)]
+ ser = pd.Series(data, dtype=ArrowDtype(pa.duration("ns")))
+
+ result = ser.dt.to_pytimedelta()
+ expected = np.array(data, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+ assert all(type(res) is timedelta for res in result)
+
+ expected = ser.astype("timedelta64[ns]").dt.to_pytimedelta()
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_dt_components():
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = ser.dt.components
+ expected = pd.DataFrame(
+ [[1, 0, 0, 2, 0, 3, 4], [None, None, None, None, None, None, None]],
+ columns=[
+ "days",
+ "hours",
+ "minutes",
+ "seconds",
+ "milliseconds",
+ "microseconds",
+ "nanoseconds",
+ ],
+ dtype="int32[pyarrow]",
+ )
+ tm.assert_frame_equal(result, expected)
+
+
@pytest.mark.parametrize("skipna", [True, False])
def test_boolean_reduce_series_all_null(all_boolean_reductions, skipna):
# GH51624
| Backport PR #56650: ENH: Implement dt methods for pyarrow duration types | https://api.github.com/repos/pandas-dev/pandas/pulls/56656 | 2023-12-28T15:46:58Z | 2023-12-28T16:16:27Z | 2023-12-28T16:16:27Z | 2023-12-28T16:16:27Z |
Backport PR #56647 on branch 2.2.x (floordiv fix for large values) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..2fcab46c9e229 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -727,6 +727,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
Conversion
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index de1ed9ecfdaf1..59f0a3af2b1ab 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -114,7 +114,12 @@ def cast_for_truediv(
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
- return arrow_array.cast(pa.float64())
+ # https://github.com/apache/arrow/issues/35563
+ # Arrow does not allow safe casting large integral values to float64.
+ # Intentionally not using arrow_array.cast because it could be a scalar
+ # value in reflected case, and safe=False only added to
+ # scalar cast in pyarrow 13.
+ return pc.cast(arrow_array, pa.float64(), safe=False)
return arrow_array
def floordiv_compat(
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 5624acfb64764..643a42d32ebe2 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3133,6 +3133,14 @@ def test_arrow_floordiv():
tm.assert_series_equal(result, expected)
+def test_arrow_floordiv_large_values():
+ # GH 55561
+ a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
+ expected = pd.Series([1425801600000], dtype="int64[pyarrow]")
+ result = a // 1_000_000
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| Backport PR #56647: floordiv fix for large values | https://api.github.com/repos/pandas-dev/pandas/pulls/56655 | 2023-12-28T15:38:51Z | 2023-12-28T16:16:37Z | 2023-12-28T16:16:37Z | 2023-12-28T16:16:37Z |
BUG: assert_series_equal not properly respecting check-dtype | diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 800b03707540f..d0f38c85868d4 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -949,9 +949,15 @@ def assert_series_equal(
obj=str(obj),
)
else:
+ # convert both to NumPy if not, check_dtype would raise earlier
+ lv, rv = left_values, right_values
+ if isinstance(left_values, ExtensionArray):
+ lv = left_values.to_numpy()
+ if isinstance(right_values, ExtensionArray):
+ rv = right_values.to_numpy()
assert_numpy_array_equal(
- left_values,
- right_values,
+ lv,
+ rv,
check_dtype=check_dtype,
obj=str(obj),
index_values=left.index,
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index aaf49f53ba02b..e38144f4c615b 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -421,16 +421,6 @@ def test_index_from_listlike_with_dtype(self, data):
def test_EA_types(self, engine, data, request):
super().test_EA_types(engine, data, request)
- @pytest.mark.xfail(reason="Expect NumpyEA, get np.ndarray")
- def test_compare_array(self, data, comparison_op):
- super().test_compare_array(data, comparison_op)
-
- def test_compare_scalar(self, data, comparison_op, request):
- if data.dtype.kind == "f" or comparison_op.__name__ in ["eq", "ne"]:
- mark = pytest.mark.xfail(reason="Expect NumpyEA, get np.ndarray")
- request.applymarker(mark)
- super().test_compare_scalar(data, comparison_op)
-
class Test2DCompat(base.NDArrayBacked2DTests):
pass
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index a074898f6046d..79132591b15b3 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -211,10 +211,7 @@ def test_assert_frame_equal_extension_dtype_mismatch():
"\\[right\\]: int[32|64]"
)
- # TODO: this shouldn't raise (or should raise a better error message)
- # https://github.com/pandas-dev/pandas/issues/56131
- with pytest.raises(AssertionError, match="classes are different"):
- tm.assert_frame_equal(left, right, check_dtype=False)
+ tm.assert_frame_equal(left, right, check_dtype=False)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(left, right, check_dtype=True)
@@ -246,7 +243,6 @@ def test_assert_frame_equal_ignore_extension_dtype_mismatch():
tm.assert_frame_equal(left, right, check_dtype=False)
-@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131")
def test_assert_frame_equal_ignore_extension_dtype_mismatch_cross_class():
# https://github.com/pandas-dev/pandas/issues/35715
left = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
@@ -300,9 +296,7 @@ def test_frame_equal_mixed_dtypes(frame_or_series, any_numeric_ea_dtype, indexer
dtypes = (any_numeric_ea_dtype, "int64")
obj1 = frame_or_series([1, 2], dtype=dtypes[indexer[0]])
obj2 = frame_or_series([1, 2], dtype=dtypes[indexer[1]])
- msg = r'(Series|DataFrame.iloc\[:, 0\] \(column name="0"\) classes) are different'
- with pytest.raises(AssertionError, match=msg):
- tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
+ tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
def test_assert_frame_equal_check_like_different_indexes():
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index f722f619bc456..c4ffc197298f0 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -290,10 +290,7 @@ def test_assert_series_equal_extension_dtype_mismatch():
\\[left\\]: Int64
\\[right\\]: int[32|64]"""
- # TODO: this shouldn't raise (or should raise a better error message)
- # https://github.com/pandas-dev/pandas/issues/56131
- with pytest.raises(AssertionError, match="Series classes are different"):
- tm.assert_series_equal(left, right, check_dtype=False)
+ tm.assert_series_equal(left, right, check_dtype=False)
with pytest.raises(AssertionError, match=msg):
tm.assert_series_equal(left, right, check_dtype=True)
@@ -372,7 +369,6 @@ def test_assert_series_equal_ignore_extension_dtype_mismatch():
tm.assert_series_equal(left, right, check_dtype=False)
-@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131")
def test_assert_series_equal_ignore_extension_dtype_mismatch_cross_class():
# https://github.com/pandas-dev/pandas/issues/35715
left = Series([1, 2, 3], dtype="Int64")
@@ -456,3 +452,13 @@ def test_large_unequal_ints(dtype):
right = Series([1577840521123543], dtype=dtype)
with pytest.raises(AssertionError, match="Series are different"):
tm.assert_series_equal(left, right)
+
+
+@pytest.mark.parametrize("dtype", [None, object])
+@pytest.mark.parametrize("check_exact", [True, False])
+@pytest.mark.parametrize("val", [3, 3.5])
+def test_ea_and_numpy_no_dtype_check(val, check_exact, dtype):
+ # GH#56651
+ left = Series([1, 2, val], dtype=dtype)
+ right = Series(pd.array([1, 2, val]))
+ tm.assert_series_equal(left, right, check_dtype=False, check_exact=check_exact)
| - [ ] closes #56651 (Replace xxxx with the GitHub issue number)
- [ ] closes #56340
- [ ] closes #56131
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56654 | 2023-12-28T15:34:16Z | 2023-12-28T21:44:04Z | 2023-12-28T21:44:04Z | 2023-12-28T21:44:07Z |
BUG: bar and line plots are not aligned on the x-axis/xticks | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index d9ab0452c8334..3d228cd2bc609 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -882,6 +882,7 @@ Plotting
^^^^^^^^
- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a Matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
- Bug in :meth:`DataFrame.plot.scatter` discarding string columns (:issue:`56142`)
+- Bug in :meth:`DataFrame.plot` where bar and line plots are not aligned on the x-axis (:issue:`56611`)
- Bug in :meth:`Series.plot` when reusing an ``ax`` object failing to raise when a ``how`` keyword is passed (:issue:`55953`)
Groupby/resample/rolling
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 6fa75ba5fb12d..56f01d1b1ee85 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -1804,6 +1804,13 @@ def _kind(self) -> Literal["bar", "barh"]:
def orientation(self) -> PlottingOrientation:
return "vertical"
+ @final
+ def _set_tick_pos(self, data) -> np.ndarray:
+ if self._is_series and is_integer_dtype(data.index):
+ return np.array(data.index)
+ else:
+ return np.arange(len(data))
+
def __init__(
self,
data,
@@ -1822,7 +1829,6 @@ def __init__(
self.bar_width = width
self._align = align
self._position = position
- self.tick_pos = np.arange(len(data))
if is_list_like(bottom):
bottom = np.array(bottom)
@@ -1835,6 +1841,8 @@ def __init__(
MPLPlot.__init__(self, data, **kwargs)
+ self.tick_pos = self._set_tick_pos(data)
+
@cache_readonly
def ax_pos(self) -> np.ndarray:
return self.tick_pos - self.tickoffset
diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py
index 2b2f2f3b84307..2f63ec137f2b2 100644
--- a/pandas/tests/plotting/test_series.py
+++ b/pandas/tests/plotting/test_series.py
@@ -919,10 +919,7 @@ def test_plot_order(self, data, index):
ax = ser.plot(kind="bar")
expected = ser.tolist()
- result = [
- patch.get_bbox().ymax
- for patch in sorted(ax.patches, key=lambda patch: patch.get_bbox().xmax)
- ]
+ result = [patch.get_bbox().ymax for patch in ax.patches]
assert expected == result
def test_style_single_ok(self):
@@ -977,6 +974,31 @@ def test_series_none_color(self):
expected = _unpack_cycler(mpl.pyplot.rcParams)[:1]
_check_colors(ax.get_lines(), linecolors=expected)
+ def test_bar_plot_x_axis(self):
+ df = DataFrame(
+ {
+ "bars": {-1: 0.5, 0: 1.0, 1: 3.0, 2: 3.5, 3: 1.5},
+ "pct": {-1: 1.0, 0: 2.0, 1: 3.0, 2: 4.0, 3: 8.0},
+ }
+ )
+ ax_bar = df["bars"].plot(kind="bar")
+ df["pct"].plot(kind="line")
+ actual_bar_x = [ax.get_x() + ax.get_width() / 2.0 for ax in ax_bar.patches]
+ expected_x = [-1, 0, 1, 2, 3]
+ assert actual_bar_x == expected_x
+
+ def test_non_numeric_bar_plot_x_axis(self):
+ df = DataFrame(
+ {
+ "bars": {"a": 0.5, "b": 1.0},
+ "pct": {"a": 4.0, "b": 2.0},
+ }
+ )
+ ax_bar = df["bars"].plot(kind="bar")
+ actual_bar_x = [ax.get_x() + ax.get_width() / 2.0 for ax in ax_bar.patches]
+ expected_x = [0, 1]
+ assert actual_bar_x == expected_x
+
@pytest.mark.slow
def test_plot_no_warning(self, ts):
# GH 55138
| - [x] closes #56460
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Added a test which will fail on main's self.tick_pos = np.arange(len(data)), which in this test will result in actual_bar_x of [0,1,2,3,4].
```
def test_bar_plot_x_axis(self, plot_data):
df = DataFrame(plot_data)
ax_bar = df["bars"].plot(kind="bar")
df["pct"].plot(kind="line")
actual_bar_x = [bar.get_x() + bar.get_width() / 2.0 for bar in ax_bar.patches]
expected_x = [-1, 0, 1, 2, 3]
assert actual_bar_x == expected_x
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/56653 | 2023-12-28T14:34:33Z | 2024-02-04T14:29:52Z | null | 2024-02-04T14:29:52Z |
ENH: Implement dt methods for pyarrow duration types | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..f7e1cc9cbe36d 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -316,6 +316,7 @@ Other enhancements
- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
+- Implemented :meth:`Series.dt` methods and attributes for :class:`ArrowDtype` with ``pyarrow.duration`` type (:issue:`52284`)
- Implemented :meth:`Series.str.extract` for :class:`ArrowDtype` (:issue:`56268`)
- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as ``"BMS"`` (:issue:`56243`)
- Improved error message when constructing :class:`Period` with invalid offsets such as ``"QS"`` (:issue:`55785`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 23b5448029dd9..5d0be2aac47c4 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -17,6 +17,7 @@
from pandas._libs import lib
from pandas._libs.tslibs import (
+ NaT,
Timedelta,
Timestamp,
timezones,
@@ -2489,6 +2490,92 @@ def _str_wrap(self, width: int, **kwargs):
result = self._apply_elementwise(predicate)
return type(self)(pa.chunked_array(result))
+ @property
+ def _dt_days(self):
+ return type(self)(
+ pa.array(self._to_timedeltaarray().days, from_pandas=True, type=pa.int32())
+ )
+
+ @property
+ def _dt_hours(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.hours if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_minutes(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.minutes if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_seconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().seconds, from_pandas=True, type=pa.int32()
+ )
+ )
+
+ @property
+ def _dt_milliseconds(self):
+ return type(self)(
+ pa.array(
+ [
+ td.components.milliseconds if td is not NaT else None
+ for td in self._to_timedeltaarray()
+ ],
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_microseconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().microseconds,
+ from_pandas=True,
+ type=pa.int32(),
+ )
+ )
+
+ @property
+ def _dt_nanoseconds(self):
+ return type(self)(
+ pa.array(
+ self._to_timedeltaarray().nanoseconds, from_pandas=True, type=pa.int32()
+ )
+ )
+
+ def _dt_to_pytimedelta(self):
+ data = self._pa_array.to_pylist()
+ if self._dtype.pyarrow_dtype.unit == "ns":
+ data = [None if ts is None else ts.to_pytimedelta() for ts in data]
+ return np.array(data, dtype=object)
+
+ def _dt_total_seconds(self):
+ return type(self)(
+ pa.array(self._to_timedeltaarray().total_seconds(), from_pandas=True)
+ )
+
+ def _dt_as_unit(self, unit: str):
+ if pa.types.is_date(self.dtype.pyarrow_dtype):
+ raise NotImplementedError("as_unit not implemented for date types")
+ pd_array = self._maybe_convert_datelike_array()
+ # Don't just cast _pa_array in order to follow pandas unit conversion rules
+ return type(self)(pa.array(pd_array.as_unit(unit), from_pandas=True))
+
@property
def _dt_year(self):
return type(self)(pc.year(self._pa_array))
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 929c7f4a63f8f..7e3ba4089ff60 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -148,6 +148,20 @@ def _delegate_method(self, name: str, *args, **kwargs):
return result
+@delegate_names(
+ delegate=ArrowExtensionArray,
+ accessors=TimedeltaArray._datetimelike_ops,
+ typ="property",
+ accessor_mapping=lambda x: f"_dt_{x}",
+ raise_on_missing=False,
+)
+@delegate_names(
+ delegate=ArrowExtensionArray,
+ accessors=TimedeltaArray._datetimelike_methods,
+ typ="method",
+ accessor_mapping=lambda x: f"_dt_{x}",
+ raise_on_missing=False,
+)
@delegate_names(
delegate=ArrowExtensionArray,
accessors=DatetimeArray._datetimelike_ops,
@@ -213,6 +227,9 @@ def _delegate_method(self, name: str, *args, **kwargs):
return result
+ def to_pytimedelta(self):
+ return cast(ArrowExtensionArray, self._parent.array)._dt_to_pytimedelta()
+
def to_pydatetime(self):
# GH#20306
warnings.warn(
@@ -241,6 +258,26 @@ def isocalendar(self) -> DataFrame:
)
return iso_calendar_df
+ @property
+ def components(self) -> DataFrame:
+ from pandas import DataFrame
+
+ components_df = DataFrame(
+ {
+ col: getattr(self._parent.array, f"_dt_{col}")
+ for col in [
+ "days",
+ "hours",
+ "minutes",
+ "seconds",
+ "milliseconds",
+ "microseconds",
+ "nanoseconds",
+ ]
+ }
+ )
+ return components_df
+
@delegate_names(
delegate=DatetimeArray,
@@ -592,7 +629,7 @@ def __new__(cls, data: Series): # pyright: ignore[reportInconsistentConstructor
index=orig.index,
)
- if isinstance(data.dtype, ArrowDtype) and data.dtype.kind == "M":
+ if isinstance(data.dtype, ArrowDtype) and data.dtype.kind in "Mm":
return ArrowTemporalProperties(data, orig)
if lib.is_np_dtype(data.dtype, "M"):
return DatetimeProperties(data, orig)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 3b03272f18203..dad2c0ce5995a 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -2723,6 +2723,111 @@ def test_dt_tz_convert(unit):
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("dtype", ["timestamp[ms][pyarrow]", "duration[ms][pyarrow]"])
+def test_as_unit(dtype):
+ # GH 52284
+ ser = pd.Series([1000, None], dtype=dtype)
+ result = ser.dt.as_unit("ns")
+ expected = ser.astype(dtype.replace("ms", "ns"))
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "prop, expected",
+ [
+ ["days", 1],
+ ["seconds", 2],
+ ["microseconds", 3],
+ ["nanoseconds", 4],
+ ],
+)
+def test_dt_timedelta_properties(prop, expected):
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = getattr(ser.dt, prop)
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([expected, None], type=pa.int32()))
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_timedelta_total_seconds():
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = ser.dt.total_seconds()
+ expected = pd.Series(
+ ArrowExtensionArray(pa.array([86402.000003, None], type=pa.float64()))
+ )
+ tm.assert_series_equal(result, expected)
+
+
+def test_dt_to_pytimedelta():
+ # GH 52284
+ data = [timedelta(1, 2, 3), timedelta(1, 2, 4)]
+ ser = pd.Series(data, dtype=ArrowDtype(pa.duration("ns")))
+
+ result = ser.dt.to_pytimedelta()
+ expected = np.array(data, dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
+ assert all(type(res) is timedelta for res in result)
+
+ expected = ser.astype("timedelta64[ns]").dt.to_pytimedelta()
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_dt_components():
+ # GH 52284
+ ser = pd.Series(
+ [
+ pd.Timedelta(
+ days=1,
+ seconds=2,
+ microseconds=3,
+ nanoseconds=4,
+ ),
+ None,
+ ],
+ dtype=ArrowDtype(pa.duration("ns")),
+ )
+ result = ser.dt.components
+ expected = pd.DataFrame(
+ [[1, 0, 0, 2, 0, 3, 4], [None, None, None, None, None, None, None]],
+ columns=[
+ "days",
+ "hours",
+ "minutes",
+ "seconds",
+ "milliseconds",
+ "microseconds",
+ "nanoseconds",
+ ],
+ dtype="int32[pyarrow]",
+ )
+ tm.assert_frame_equal(result, expected)
+
+
@pytest.mark.parametrize("skipna", [True, False])
def test_boolean_reduce_series_all_null(all_boolean_reductions, skipna):
# GH51624
| - [x] closes #52284 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56650 | 2023-12-28T01:23:14Z | 2023-12-28T15:46:51Z | 2023-12-28T15:46:51Z | 2023-12-28T18:46:16Z |
Backport PR #56644 on branch 2.2.x (BUG: Series.to_numpy raising for arrow floats to numpy floats) | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 23b5448029dd9..de1ed9ecfdaf1 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -37,6 +37,7 @@
CategoricalDtype,
is_array_like,
is_bool_dtype,
+ is_float_dtype,
is_integer,
is_list_like,
is_numeric_dtype,
@@ -1320,6 +1321,7 @@ def to_numpy(
copy: bool = False,
na_value: object = lib.no_default,
) -> np.ndarray:
+ original_na_value = na_value
dtype, na_value = to_numpy_dtype_inference(self, dtype, na_value, self._hasna)
pa_type = self._pa_array.type
if not self._hasna or isna(na_value) or pa.types.is_null(pa_type):
@@ -1345,7 +1347,14 @@ def to_numpy(
if dtype is not None and isna(na_value):
na_value = None
result = np.full(len(data), fill_value=na_value, dtype=dtype)
- elif not data._hasna or (pa.types.is_floating(pa_type) and na_value is np.nan):
+ elif not data._hasna or (
+ pa.types.is_floating(pa_type)
+ and (
+ na_value is np.nan
+ or original_na_value is lib.no_default
+ and is_float_dtype(dtype)
+ )
+ ):
result = data._pa_array.to_numpy()
if dtype is not None:
result = result.astype(dtype, copy=False)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 3b03272f18203..5624acfb64764 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3153,6 +3153,14 @@ def test_string_to_time_parsing_cast():
tm.assert_series_equal(result, expected)
+def test_to_numpy_float():
+ # GH#56267
+ ser = pd.Series([32, 40, None], dtype="float[pyarrow]")
+ result = ser.astype("float64")
+ expected = pd.Series([32, 40, np.nan], dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+
def test_to_numpy_timestamp_to_int():
# GH 55997
ser = pd.Series(["2020-01-01 04:30:00"], dtype="timestamp[ns][pyarrow]")
| Backport PR #56644: BUG: Series.to_numpy raising for arrow floats to numpy floats | https://api.github.com/repos/pandas-dev/pandas/pulls/56648 | 2023-12-28T00:02:47Z | 2023-12-28T01:25:53Z | 2023-12-28T01:25:53Z | 2023-12-28T01:25:53Z |
floordiv fix for large values | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..2fcab46c9e229 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -727,6 +727,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
+- Bug in :meth:`Series.__floordiv__` for :class:`ArrowDtype` with integral dtypes raising for large values (:issue:`56645`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
Conversion
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 23b5448029dd9..5d4af24221086 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -113,7 +113,12 @@ def cast_for_truediv(
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
- return arrow_array.cast(pa.float64())
+ # https://github.com/apache/arrow/issues/35563
+ # Arrow does not allow safe casting large integral values to float64.
+ # Intentionally not using arrow_array.cast because it could be a scalar
+ # value in reflected case, and safe=False only added to
+ # scalar cast in pyarrow 13.
+ return pc.cast(arrow_array, pa.float64(), safe=False)
return arrow_array
def floordiv_compat(
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 3b03272f18203..1ade1d398a4dd 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3133,6 +3133,14 @@ def test_arrow_floordiv():
tm.assert_series_equal(result, expected)
+def test_arrow_floordiv_large_values():
+ # GH 55561
+ a = pd.Series([1425801600000000000], dtype="int64[pyarrow]")
+ expected = pd.Series([1425801600000], dtype="int64[pyarrow]")
+ result = a // 1_000_000
+ tm.assert_series_equal(result, expected)
+
+
def test_string_to_datetime_parsing_cast():
# GH 56266
string_dates = ["2020-01-01 04:30:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"]
| - [ ] closes #56645 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56647 | 2023-12-27T23:47:02Z | 2023-12-28T15:37:53Z | 2023-12-28T15:37:53Z | 2023-12-28T16:41:33Z |
BUG: Series.to_numpy raising for arrow floats to numpy floats | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 23b5448029dd9..de1ed9ecfdaf1 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -37,6 +37,7 @@
CategoricalDtype,
is_array_like,
is_bool_dtype,
+ is_float_dtype,
is_integer,
is_list_like,
is_numeric_dtype,
@@ -1320,6 +1321,7 @@ def to_numpy(
copy: bool = False,
na_value: object = lib.no_default,
) -> np.ndarray:
+ original_na_value = na_value
dtype, na_value = to_numpy_dtype_inference(self, dtype, na_value, self._hasna)
pa_type = self._pa_array.type
if not self._hasna or isna(na_value) or pa.types.is_null(pa_type):
@@ -1345,7 +1347,14 @@ def to_numpy(
if dtype is not None and isna(na_value):
na_value = None
result = np.full(len(data), fill_value=na_value, dtype=dtype)
- elif not data._hasna or (pa.types.is_floating(pa_type) and na_value is np.nan):
+ elif not data._hasna or (
+ pa.types.is_floating(pa_type)
+ and (
+ na_value is np.nan
+ or original_na_value is lib.no_default
+ and is_float_dtype(dtype)
+ )
+ ):
result = data._pa_array.to_numpy()
if dtype is not None:
result = result.astype(dtype, copy=False)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 3b03272f18203..5624acfb64764 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -3153,6 +3153,14 @@ def test_string_to_time_parsing_cast():
tm.assert_series_equal(result, expected)
+def test_to_numpy_float():
+ # GH#56267
+ ser = pd.Series([32, 40, None], dtype="float[pyarrow]")
+ result = ser.astype("float64")
+ expected = pd.Series([32, 40, np.nan], dtype="float64")
+ tm.assert_series_equal(result, expected)
+
+
def test_to_numpy_timestamp_to_int():
# GH 55997
ser = pd.Series(["2020-01-01 04:30:00"], dtype="timestamp[ns][pyarrow]")
| - [ ] xref #56267 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56644 | 2023-12-27T21:36:29Z | 2023-12-28T00:02:39Z | 2023-12-28T00:02:39Z | 2023-12-28T15:22:37Z |
TYP: Fix some PythonParser and Plotting types | diff --git a/pandas/core/interchange/from_dataframe.py b/pandas/core/interchange/from_dataframe.py
index d45ae37890ba7..73f492c83c2ff 100644
--- a/pandas/core/interchange/from_dataframe.py
+++ b/pandas/core/interchange/from_dataframe.py
@@ -2,7 +2,10 @@
import ctypes
import re
-from typing import Any
+from typing import (
+ Any,
+ overload,
+)
import numpy as np
@@ -459,12 +462,42 @@ def buffer_to_ndarray(
return np.array([], dtype=ctypes_type)
+@overload
+def set_nulls(
+ data: np.ndarray,
+ col: Column,
+ validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
+ allow_modify_inplace: bool = ...,
+) -> np.ndarray:
+ ...
+
+
+@overload
+def set_nulls(
+ data: pd.Series,
+ col: Column,
+ validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
+ allow_modify_inplace: bool = ...,
+) -> pd.Series:
+ ...
+
+
+@overload
+def set_nulls(
+ data: np.ndarray | pd.Series,
+ col: Column,
+ validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
+ allow_modify_inplace: bool = ...,
+) -> np.ndarray | pd.Series:
+ ...
+
+
def set_nulls(
data: np.ndarray | pd.Series,
col: Column,
validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
allow_modify_inplace: bool = True,
-):
+) -> np.ndarray | pd.Series:
"""
Set null values for the data according to the column null kind.
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 79e7554a5744c..c1880eb815032 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -4,12 +4,6 @@
abc,
defaultdict,
)
-from collections.abc import (
- Hashable,
- Iterator,
- Mapping,
- Sequence,
-)
import csv
from io import StringIO
import re
@@ -50,15 +44,24 @@
)
if TYPE_CHECKING:
+ from collections.abc import (
+ Hashable,
+ Iterator,
+ Mapping,
+ Sequence,
+ )
+
from pandas._typing import (
ArrayLike,
ReadCsvBuffer,
Scalar,
+ T,
)
from pandas import (
Index,
MultiIndex,
+ Series,
)
# BOM character (byte order mark)
@@ -77,7 +80,7 @@ def __init__(self, f: ReadCsvBuffer[str] | list, **kwds) -> None:
"""
super().__init__(kwds)
- self.data: Iterator[str] | None = None
+ self.data: Iterator[list[str]] | list[list[Scalar]] = []
self.buf: list = []
self.pos = 0
self.line_pos = 0
@@ -116,10 +119,11 @@ def __init__(self, f: ReadCsvBuffer[str] | list, **kwds) -> None:
# Set self.data to something that can read lines.
if isinstance(f, list):
- # read_excel: f is a list
- self.data = cast(Iterator[str], f)
+ # read_excel: f is a nested list, can contain non-str
+ self.data = f
else:
assert hasattr(f, "readline")
+ # yields list of str
self.data = self._make_reader(f)
# Get columns in two steps: infer from data, then
@@ -179,7 +183,7 @@ def num(self) -> re.Pattern:
)
return re.compile(regex)
- def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]):
+ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]) -> Iterator[list[str]]:
sep = self.delimiter
if sep is None or len(sep) == 1:
@@ -246,7 +250,9 @@ def _read():
def read(
self, rows: int | None = None
) -> tuple[
- Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
+ Index | None,
+ Sequence[Hashable] | MultiIndex,
+ Mapping[Hashable, ArrayLike | Series],
]:
try:
content = self._get_lines(rows)
@@ -326,7 +332,9 @@ def _exclude_implicit_index(
def get_chunk(
self, size: int | None = None
) -> tuple[
- Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
+ Index | None,
+ Sequence[Hashable] | MultiIndex,
+ Mapping[Hashable, ArrayLike | Series],
]:
if size is None:
# error: "PythonParser" has no attribute "chunksize"
@@ -689,7 +697,7 @@ def _check_for_bom(self, first_row: list[Scalar]) -> list[Scalar]:
new_row_list: list[Scalar] = [new_row]
return new_row_list + first_row[1:]
- def _is_line_empty(self, line: list[Scalar]) -> bool:
+ def _is_line_empty(self, line: Sequence[Scalar]) -> bool:
"""
Check if a line is empty or not.
@@ -730,8 +738,6 @@ def _next_line(self) -> list[Scalar]:
else:
while self.skipfunc(self.pos):
self.pos += 1
- # assert for mypy, data is Iterator[str] or None, would error in next
- assert self.data is not None
next(self.data)
while True:
@@ -800,12 +806,10 @@ def _next_iter_line(self, row_num: int) -> list[Scalar] | None:
The row number of the line being parsed.
"""
try:
- # assert for mypy, data is Iterator[str] or None, would error in next
- assert self.data is not None
+ assert not isinstance(self.data, list)
line = next(self.data)
- # for mypy
- assert isinstance(line, list)
- return line
+ # lie about list[str] vs list[Scalar] to minimize ignores
+ return line # type: ignore[return-value]
except csv.Error as e:
if self.on_bad_lines in (
self.BadLineHandleMethod.ERROR,
@@ -855,7 +859,7 @@ def _check_comments(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
ret.append(rl)
return ret
- def _remove_empty_lines(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ def _remove_empty_lines(self, lines: list[list[T]]) -> list[list[T]]:
"""
Iterate through the lines and remove any that are
either empty or contain only one whitespace value
@@ -1121,9 +1125,6 @@ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]:
row_ct = 0
offset = self.pos if self.pos is not None else 0
while row_ct < rows:
- # assert for mypy, data is Iterator[str] or None, would
- # error in next
- assert self.data is not None
new_row = next(self.data)
if not self.skipfunc(offset + row_index):
row_ct += 1
@@ -1338,7 +1339,7 @@ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]) -> FixedWidthReader:
self.infer_nrows,
)
- def _remove_empty_lines(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:
+ def _remove_empty_lines(self, lines: list[list[T]]) -> list[list[T]]:
"""
Returns the list of lines without the empty ones. With fixed-width
fields, empty lines become arrays of empty strings.
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py
index d2b76decaa75d..084452ec23719 100644
--- a/pandas/plotting/_matplotlib/boxplot.py
+++ b/pandas/plotting/_matplotlib/boxplot.py
@@ -371,8 +371,8 @@ def _get_colors():
# num_colors=3 is required as method maybe_color_bp takes the colors
# in positions 0 and 2.
# if colors not provided, use same defaults as DataFrame.plot.box
- result = get_standard_colors(num_colors=3)
- result = np.take(result, [0, 0, 2])
+ result_list = get_standard_colors(num_colors=3)
+ result = np.take(result_list, [0, 0, 2])
result = np.append(result, "k")
colors = kwds.pop("color", None)
diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py
index e610f1adb602c..898abc9b78e3f 100644
--- a/pandas/plotting/_matplotlib/hist.py
+++ b/pandas/plotting/_matplotlib/hist.py
@@ -457,10 +457,8 @@ def hist_series(
ax.grid(grid)
axes = np.array([ax])
- # error: Argument 1 to "set_ticks_props" has incompatible type "ndarray[Any,
- # dtype[Any]]"; expected "Axes | Sequence[Axes]"
set_ticks_props(
- axes, # type: ignore[arg-type]
+ axes,
xlabelsize=xlabelsize,
xrot=xrot,
ylabelsize=ylabelsize,
diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py
index bf4e4be3bfd82..45a077a6151cf 100644
--- a/pandas/plotting/_matplotlib/style.py
+++ b/pandas/plotting/_matplotlib/style.py
@@ -3,11 +3,13 @@
from collections.abc import (
Collection,
Iterator,
+ Sequence,
)
import itertools
from typing import (
TYPE_CHECKING,
cast,
+ overload,
)
import warnings
@@ -26,12 +28,46 @@
from matplotlib.colors import Colormap
+@overload
+def get_standard_colors(
+ num_colors: int,
+ colormap: Colormap | None = ...,
+ color_type: str = ...,
+ *,
+ color: dict[str, Color],
+) -> dict[str, Color]:
+ ...
+
+
+@overload
+def get_standard_colors(
+ num_colors: int,
+ colormap: Colormap | None = ...,
+ color_type: str = ...,
+ *,
+ color: Color | Sequence[Color] | None = ...,
+) -> list[Color]:
+ ...
+
+
+@overload
+def get_standard_colors(
+ num_colors: int,
+ colormap: Colormap | None = ...,
+ color_type: str = ...,
+ *,
+ color: dict[str, Color] | Color | Sequence[Color] | None = ...,
+) -> dict[str, Color] | list[Color]:
+ ...
+
+
def get_standard_colors(
num_colors: int,
colormap: Colormap | None = None,
color_type: str = "default",
- color: dict[str, Color] | Color | Collection[Color] | None = None,
-):
+ *,
+ color: dict[str, Color] | Color | Sequence[Color] | None = None,
+) -> dict[str, Color] | list[Color]:
"""
Get standard colors based on `colormap`, `color_type` or `color` inputs.
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index 898b5b25e7b01..89a8a7cf79719 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -19,10 +19,7 @@
)
if TYPE_CHECKING:
- from collections.abc import (
- Iterable,
- Sequence,
- )
+ from collections.abc import Iterable
from matplotlib.axes import Axes
from matplotlib.axis import Axis
@@ -442,7 +439,7 @@ def handle_shared_axes(
_remove_labels_from_axis(ax.yaxis)
-def flatten_axes(axes: Axes | Sequence[Axes]) -> np.ndarray:
+def flatten_axes(axes: Axes | Iterable[Axes]) -> np.ndarray:
if not is_list_like(axes):
return np.array([axes])
elif isinstance(axes, (np.ndarray, ABCIndex)):
@@ -451,7 +448,7 @@ def flatten_axes(axes: Axes | Sequence[Axes]) -> np.ndarray:
def set_ticks_props(
- axes: Axes | Sequence[Axes],
+ axes: Axes | Iterable[Axes],
xlabelsize: int | None = None,
xrot=None,
ylabelsize: int | None = None,
diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json
index a38343d6198ae..da27906e041cf 100644
--- a/pyright_reportGeneralTypeIssues.json
+++ b/pyright_reportGeneralTypeIssues.json
@@ -99,11 +99,11 @@
"pandas/io/parsers/base_parser.py",
"pandas/io/parsers/c_parser_wrapper.py",
"pandas/io/pytables.py",
- "pandas/io/sas/sas_xport.py",
"pandas/io/sql.py",
"pandas/io/stata.py",
"pandas/plotting/_matplotlib/boxplot.py",
"pandas/plotting/_matplotlib/core.py",
+ "pandas/plotting/_matplotlib/misc.py",
"pandas/plotting/_matplotlib/timeseries.py",
"pandas/plotting/_matplotlib/tools.py",
"pandas/tseries/frequencies.py",
| and a few misc types. | https://api.github.com/repos/pandas-dev/pandas/pulls/56643 | 2023-12-27T21:32:44Z | 2023-12-27T23:38:23Z | 2023-12-27T23:38:23Z | 2024-01-17T02:49:50Z |
DOC: Add optional dependencies table in 2.2 whatsnew | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..5a3a7c8a30e9f 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -416,15 +416,63 @@ Backwards incompatible API changes
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
-The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
-Optional libraries below the lowest tested version may still work, but are not considered supported.
-
-+-----------------+-----------------+---------+
-| Package | Minimum Version | Changed |
-+=================+=================+=========+
-| mypy (dev) | 1.8.0 | X |
-+-----------------+-----------------+---------+
+For `optional dependencies <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
+Optional dependencies below the lowest tested version may still work but are not considered supported.
+The following table lists the optional dependencies that have had their minimum tested version increased.
+
++-----------------+---------------------+
+| Package | New Minimum Version |
++=================+=====================+
+| beautifulsoup4 | 4.11.2 |
++-----------------+---------------------+
+| blosc | 1.21.3 |
++-----------------+---------------------+
+| bottleneck | 1.3.6 |
++-----------------+---------------------+
+| fastparquet | 2022.12.0 |
++-----------------+---------------------+
+| fsspec | 2022.11.0 |
++-----------------+---------------------+
+| gcsfs | 2022.11.0 |
++-----------------+---------------------+
+| lxml | 4.9.2 |
++-----------------+---------------------+
+| matplotlib | 3.6.3 |
++-----------------+---------------------+
+| numba | 0.56.4 |
++-----------------+---------------------+
+| numexpr | 2.8.4 |
++-----------------+---------------------+
+| qtpy | 2.3.0 |
++-----------------+---------------------+
+| openpyxl | 3.1.0 |
++-----------------+---------------------+
+| psycopg2 | 2.9.6 |
++-----------------+---------------------+
+| pyreadstat | 1.2.0 |
++-----------------+---------------------+
+| pytables | 3.8.0 |
++-----------------+---------------------+
+| pyxlsb | 1.0.10 |
++-----------------+---------------------+
+| s3fs | 2022.11.0 |
++-----------------+---------------------+
+| scipy | 1.10.0 |
++-----------------+---------------------+
+| sqlalchemy | 2.0.0 |
++-----------------+---------------------+
+| tabulate | 0.9.0 |
++-----------------+---------------------+
+| xarray | 2022.12.0 |
++-----------------+---------------------+
+| xlsxwriter | 3.0.5 |
++-----------------+---------------------+
+| zstandard | 0.19.0 |
++-----------------+---------------------+
+| pyqt5 | 5.15.8 |
++-----------------+---------------------+
+| tzdata | 2022.7 |
++-----------------+---------------------+
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56641 | 2023-12-27T19:54:04Z | 2023-12-28T19:03:52Z | 2023-12-28T19:03:52Z | 2023-12-28T19:03:55Z |
Backport PR #56632 on branch 2.2.x (DOC: Minor fixups for 2.2.0 whatsnew) | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5ee94b74c527e..5b955aa45219a 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -123,7 +123,7 @@ nullability handling.
with pg_dbapi.connect(uri) as conn:
df.to_sql("pandas_table", conn, index=False)
- # for roundtripping
+ # for round-tripping
with pg_dbapi.connect(uri) as conn:
df2 = pd.read_sql("pandas_table", conn)
@@ -176,7 +176,7 @@ leverage the ``dtype_backend="pyarrow"`` argument of :func:`~pandas.read_sql`
.. code-block:: ipython
- # for roundtripping
+ # for round-tripping
with pg_dbapi.connect(uri) as conn:
df2 = pd.read_sql("pandas_table", conn, dtype_backend="pyarrow")
@@ -306,22 +306,21 @@ Other enhancements
- :meth:`~DataFrame.to_sql` with method parameter set to ``multi`` works with Oracle on the backend
- :attr:`Series.attrs` / :attr:`DataFrame.attrs` now uses a deepcopy for propagating ``attrs`` (:issue:`54134`).
- :func:`get_dummies` now returning extension dtypes ``boolean`` or ``bool[pyarrow]`` that are compatible with the input dtype (:issue:`56273`)
-- :func:`read_csv` now supports ``on_bad_lines`` parameter with ``engine="pyarrow"``. (:issue:`54480`)
+- :func:`read_csv` now supports ``on_bad_lines`` parameter with ``engine="pyarrow"`` (:issue:`54480`)
- :func:`read_sas` returns ``datetime64`` dtypes with resolutions better matching those stored natively in SAS, and avoids returning object-dtype in cases that cannot be stored with ``datetime64[ns]`` dtype (:issue:`56127`)
-- :func:`read_spss` now returns a :class:`DataFrame` that stores the metadata in :attr:`DataFrame.attrs`. (:issue:`54264`)
+- :func:`read_spss` now returns a :class:`DataFrame` that stores the metadata in :attr:`DataFrame.attrs` (:issue:`54264`)
- :func:`tseries.api.guess_datetime_format` is now part of the public API (:issue:`54727`)
+- :meth:`DataFrame.apply` now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- :meth:`ExtensionArray._explode` interface method added to allow extension type implementations of the ``explode`` method (:issue:`54833`)
- :meth:`ExtensionArray.duplicated` added to allow extension type implementations of the ``duplicated`` method (:issue:`55255`)
- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
-- DataFrame.apply now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
- Implemented :meth:`Series.str.extract` for :class:`ArrowDtype` (:issue:`56268`)
-- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as "BMS" (:issue:`56243`)
-- Improved error message when constructing :class:`Period` with invalid offsets such as "QS" (:issue:`55785`)
+- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as ``"BMS"`` (:issue:`56243`)
+- Improved error message when constructing :class:`Period` with invalid offsets such as ``"QS"`` (:issue:`55785`)
- The dtypes ``string[pyarrow]`` and ``string[pyarrow_numpy]`` now both utilize the ``large_string`` type from PyArrow to avoid overflow for long columns (:issue:`56259`)
-
.. ---------------------------------------------------------------------------
.. _whatsnew_220.notable_bug_fixes:
@@ -386,6 +385,8 @@ index levels when joining on two indexes with different levels (:issue:`34133`).
left = pd.DataFrame({"left": 1}, index=pd.MultiIndex.from_tuples([("x", 1), ("x", 2)], names=["A", "B"]))
right = pd.DataFrame({"right": 2}, index=pd.MultiIndex.from_tuples([(1, 1), (2, 2)], names=["B", "C"]))
+ left
+ right
result = left.join(right)
*Old Behavior*
@@ -415,15 +416,6 @@ Backwards incompatible API changes
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Some minimum supported versions of dependencies were updated.
-If installed, we now require:
-
-+-----------------+-----------------+----------+---------+
-| Package | Minimum Version | Required | Changed |
-+=================+=================+==========+=========+
-| | | X | X |
-+-----------------+-----------------+----------+---------+
-
For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
Optional libraries below the lowest tested version may still work, but are not considered supported.
@@ -433,8 +425,6 @@ Optional libraries below the lowest tested version may still work, but are not c
+=================+=================+=========+
| mypy (dev) | 1.8.0 | X |
+-----------------+-----------------+---------+
-| | | X |
-+-----------------+-----------------+---------+
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
@@ -606,20 +596,20 @@ Other Deprecations
- Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`)
- Deprecated accepting a type as an argument in :meth:`Index.view`, call without any arguments instead (:issue:`55709`)
- Deprecated allowing non-integer ``periods`` argument in :func:`date_range`, :func:`timedelta_range`, :func:`period_range`, and :func:`interval_range` (:issue:`56036`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard`. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict`. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_excel` except ``excel_writer``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_gbq` except ``destination_table``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_hdf` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_html` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_json` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_latex` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_markdown` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_parquet` except ``path``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_xml` except ``path_or_buffer``. (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_excel` except ``excel_writer`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_gbq` except ``destination_table`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_hdf` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_html` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_json` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_latex` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_markdown` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_parquet` except ``path`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_xml` except ``path_or_buffer`` (:issue:`54229`)
- Deprecated allowing passing :class:`BlockManager` objects to :class:`DataFrame` or :class:`SingleBlockManager` objects to :class:`Series` (:issue:`52419`)
- Deprecated behavior of :meth:`Index.insert` with an object-dtype index silently performing type inference on the result, explicitly call ``result.infer_objects(copy=False)`` for the old behavior instead (:issue:`51363`)
- Deprecated casting non-datetimelike values (mainly strings) in :meth:`Series.isin` and :meth:`Index.isin` with ``datetime64``, ``timedelta64``, and :class:`PeriodDtype` dtypes (:issue:`53111`)
@@ -692,31 +682,30 @@ Bug fixes
Categorical
^^^^^^^^^^^
- :meth:`Categorical.isin` raising ``InvalidIndexError`` for categorical containing overlapping :class:`Interval` values (:issue:`34974`)
-- Bug in :meth:`CategoricalDtype.__eq__` returning false for unordered categorical data with mixed types (:issue:`55468`)
--
+- Bug in :meth:`CategoricalDtype.__eq__` returning ``False`` for unordered categorical data with mixed types (:issue:`55468`)
Datetimelike
^^^^^^^^^^^^
- Bug in :class:`DatetimeIndex` construction when passing both a ``tz`` and either ``dayfirst`` or ``yearfirst`` ignoring dayfirst/yearfirst (:issue:`55813`)
- Bug in :class:`DatetimeIndex` when passing an object-dtype ndarray of float objects and a ``tz`` incorrectly localizing the result (:issue:`55780`)
- Bug in :func:`Series.isin` with :class:`DatetimeTZDtype` dtype and comparison values that are all ``NaT`` incorrectly returning all-``False`` even if the series contains ``NaT`` entries (:issue:`56427`)
-- Bug in :func:`concat` raising ``AttributeError`` when concatenating all-NA DataFrame with :class:`DatetimeTZDtype` dtype DataFrame. (:issue:`52093`)
+- Bug in :func:`concat` raising ``AttributeError`` when concatenating all-NA DataFrame with :class:`DatetimeTZDtype` dtype DataFrame (:issue:`52093`)
- Bug in :func:`testing.assert_extension_array_equal` that could use the wrong unit when comparing resolutions (:issue:`55730`)
- Bug in :func:`to_datetime` and :class:`DatetimeIndex` when passing a list of mixed-string-and-numeric types incorrectly raising (:issue:`55780`)
- Bug in :func:`to_datetime` and :class:`DatetimeIndex` when passing mixed-type objects with a mix of timezones or mix of timezone-awareness failing to raise ``ValueError`` (:issue:`55693`)
+- Bug in :meth:`.Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in :meth:`DatetimeIndex.shift` with non-nanosecond resolution incorrectly returning with nanosecond resolution (:issue:`56117`)
- Bug in :meth:`DatetimeIndex.union` returning object dtype for tz-aware indexes with the same timezone but different units (:issue:`55238`)
- Bug in :meth:`Index.is_monotonic_increasing` and :meth:`Index.is_monotonic_decreasing` always caching :meth:`Index.is_unique` as ``True`` when first value in index is ``NaT`` (:issue:`55755`)
- Bug in :meth:`Index.view` to a datetime64 dtype with non-supported resolution incorrectly raising (:issue:`55710`)
- Bug in :meth:`Series.dt.round` with non-nanosecond resolution and ``NaT`` entries incorrectly raising ``OverflowError`` (:issue:`56158`)
- Bug in :meth:`Series.fillna` with non-nanosecond resolution dtypes and higher-resolution vector values returning incorrect (internally-corrupted) results (:issue:`56410`)
-- Bug in :meth:`Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in :meth:`Timestamp.unit` being inferred incorrectly from an ISO8601 format string with minute or hour resolution and a timezone offset (:issue:`56208`)
-- Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetim64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`)
+- Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetime64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`)
- Bug in adding or subtracting a :class:`Week` offset to a ``datetime64`` :class:`Series`, :class:`Index`, or :class:`DataFrame` column with non-nanosecond resolution returning incorrect results (:issue:`55583`)
- Bug in addition or subtraction of :class:`BusinessDay` offset with ``offset`` attribute to non-nanosecond :class:`Index`, :class:`Series`, or :class:`DataFrame` column giving incorrect results (:issue:`55608`)
- Bug in addition or subtraction of :class:`DateOffset` objects with microsecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` columns with non-nanosecond resolution (:issue:`55595`)
-- Bug in addition or subtraction of very large :class:`Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
+- Bug in addition or subtraction of very large :class:`.Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond :class:`DatetimeTZDtype` and inputs that would be out of bounds with nanosecond resolution incorrectly raising ``OutOfBoundsDatetime`` (:issue:`54620`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` (or :class:`DatetimeTZDtype`) from mixed-numeric inputs treating those as nanoseconds instead of as multiples of the dtype's unit (which would happen with non-mixed numeric inputs) (:issue:`56004`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` dtype and inputs that would be out of bounds for a ``datetime64[ns]`` incorrectly raising ``OutOfBoundsDatetime`` (:issue:`55756`)
@@ -739,14 +728,12 @@ Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
--
Conversion
^^^^^^^^^^
- Bug in :meth:`DataFrame.astype` when called with ``str`` on unpickled array - the array might change in-place (:issue:`54654`)
- Bug in :meth:`DataFrame.astype` where ``errors="ignore"`` had no effect for extension types (:issue:`54654`)
- Bug in :meth:`Series.convert_dtypes` not converting all NA column to ``null[pyarrow]`` (:issue:`55346`)
--
Strings
^^^^^^^
@@ -763,13 +750,12 @@ Strings
Interval
^^^^^^^^
-- Bug in :class:`Interval` ``__repr__`` not displaying UTC offsets for :class:`Timestamp` bounds. Additionally the hour, minute and second components will now be shown. (:issue:`55015`)
+- Bug in :class:`Interval` ``__repr__`` not displaying UTC offsets for :class:`Timestamp` bounds. Additionally the hour, minute and second components will now be shown (:issue:`55015`)
- Bug in :meth:`IntervalIndex.factorize` and :meth:`Series.factorize` with :class:`IntervalDtype` with datetime64 or timedelta64 intervals not preserving non-nanosecond units (:issue:`56099`)
- Bug in :meth:`IntervalIndex.from_arrays` when passed ``datetime64`` or ``timedelta64`` arrays with mismatched resolutions constructing an invalid ``IntervalArray`` object (:issue:`55714`)
- Bug in :meth:`IntervalIndex.get_indexer` with datetime or timedelta intervals incorrectly matching on integer targets (:issue:`47772`)
- Bug in :meth:`IntervalIndex.get_indexer` with timezone-aware datetime intervals incorrectly matching on a sequence of timezone-naive targets (:issue:`47772`)
- Bug in setting values on a :class:`Series` with an :class:`IntervalIndex` using a slice incorrectly raising (:issue:`54722`)
--
Indexing
^^^^^^^^
@@ -781,25 +767,23 @@ Indexing
Missing
^^^^^^^
- Bug in :meth:`DataFrame.update` wasn't updating in-place for tz-aware datetime64 dtypes (:issue:`56227`)
--
MultiIndex
^^^^^^^^^^
- Bug in :meth:`MultiIndex.get_indexer` not raising ``ValueError`` when ``method`` provided and index is non-monotonic (:issue:`53452`)
--
I/O
^^^
-- Bug in :func:`read_csv` where ``engine="python"`` did not respect ``chunksize`` arg when ``skiprows`` was specified. (:issue:`56323`)
-- Bug in :func:`read_csv` where ``engine="python"`` was causing a ``TypeError`` when a callable ``skiprows`` and a chunk size was specified. (:issue:`55677`)
-- Bug in :func:`read_csv` where ``on_bad_lines="warn"`` would write to ``stderr`` instead of raise a Python warning. This now yields a :class:`.errors.ParserWarning` (:issue:`54296`)
+- Bug in :func:`read_csv` where ``engine="python"`` did not respect ``chunksize`` arg when ``skiprows`` was specified (:issue:`56323`)
+- Bug in :func:`read_csv` where ``engine="python"`` was causing a ``TypeError`` when a callable ``skiprows`` and a chunk size was specified (:issue:`55677`)
+- Bug in :func:`read_csv` where ``on_bad_lines="warn"`` would write to ``stderr`` instead of raising a Python warning; this now yields a :class:`.errors.ParserWarning` (:issue:`54296`)
- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``quotechar`` was ignored (:issue:`52266`)
-- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``usecols`` wasn't working with a csv with no headers (:issue:`54459`)
-- Bug in :func:`read_excel`, with ``engine="xlrd"`` (``xls`` files) erroring when file contains NaNs/Infs (:issue:`54564`)
+- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``usecols`` wasn't working with a CSV with no headers (:issue:`54459`)
+- Bug in :func:`read_excel`, with ``engine="xlrd"`` (``xls`` files) erroring when the file contains ``NaN`` or ``Inf`` (:issue:`54564`)
- Bug in :func:`read_json` not handling dtype conversion properly if ``infer_string`` is set (:issue:`56195`)
-- Bug in :meth:`DataFrame.to_excel`, with ``OdsWriter`` (``ods`` files) writing boolean/string value (:issue:`54994`)
+- Bug in :meth:`DataFrame.to_excel`, with ``OdsWriter`` (``ods`` files) writing Boolean/string value (:issue:`54994`)
- Bug in :meth:`DataFrame.to_hdf` and :func:`read_hdf` with ``datetime64`` dtypes with non-nanosecond resolution failing to round-trip correctly (:issue:`55622`)
-- Bug in :meth:`~pandas.read_excel` with ``engine="odf"`` (``ods`` files) when string contains annotation (:issue:`55200`)
+- Bug in :meth:`~pandas.read_excel` with ``engine="odf"`` (``ods`` files) when a string cell contains an annotation (:issue:`55200`)
- Bug in :meth:`~pandas.read_excel` with an ODS file without cached formatted cell for float values (:issue:`55219`)
- Bug where :meth:`DataFrame.to_json` would raise an ``OverflowError`` instead of a ``TypeError`` with unsupported NumPy types (:issue:`55403`)
@@ -808,12 +792,11 @@ Period
- Bug in :class:`PeriodIndex` construction when more than one of ``data``, ``ordinal`` and ``**fields`` are passed failing to raise ``ValueError`` (:issue:`55961`)
- Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`)
- Bug in casting from :class:`PeriodDtype` with ``astype`` to ``datetime64`` or :class:`DatetimeTZDtype` with non-nanosecond unit incorrectly returning with nanosecond unit (:issue:`55958`)
--
Plotting
^^^^^^^^
-- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
-- Bug in :meth:`DataFrame.plot.scatter` discaring string columns (:issue:`56142`)
+- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a Matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
+- Bug in :meth:`DataFrame.plot.scatter` discarding string columns (:issue:`56142`)
- Bug in :meth:`Series.plot` when reusing an ``ax`` object failing to raise when a ``how`` keyword is passed (:issue:`55953`)
Groupby/resample/rolling
@@ -821,9 +804,9 @@ Groupby/resample/rolling
- Bug in :class:`.Rolling` where duplicate datetimelike indexes are treated as consecutive rather than equal with ``closed='left'`` and ``closed='neither'`` (:issue:`20712`)
- Bug in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, and :meth:`.SeriesGroupBy.idxmax` would not retain :class:`.Categorical` dtype when the index was a :class:`.CategoricalIndex` that contained NA values (:issue:`54234`)
- Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.SeriesGroupBy.transform` when ``observed=False`` and ``f="idxmin"`` or ``f="idxmax"`` would incorrectly raise on unobserved categories (:issue:`54234`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`55951`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`55951`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`55951`)
- Bug in :meth:`DataFrame.asfreq` and :meth:`Series.asfreq` with a :class:`DatetimeIndex` with non-nanosecond resolution incorrectly converting to nanosecond resolution (:issue:`55958`)
- Bug in :meth:`DataFrame.ewm` when passed ``times`` with non-nanosecond ``datetime64`` or :class:`DatetimeTZDtype` dtype (:issue:`56262`)
- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` where grouping by a combination of ``Decimal`` and NA values would fail when ``sort=True`` (:issue:`54847`)
@@ -845,22 +828,11 @@ Reshaping
- Bug in :meth:`DataFrame.melt` where it would not preserve the datetime (:issue:`55254`)
- Bug in :meth:`DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`)
- Bug in :meth:`DataFrame.pivot` with numeric columns and extension dtype for data (:issue:`56528`)
-- Bug in :meth:`DataFrame.stack` and :meth:`Series.stack` with ``future_stack=True`` would not preserve NA values in the index (:issue:`56573`)
+- Bug in :meth:`DataFrame.stack` with ``future_stack=True`` would not preserve NA values in the index (:issue:`56573`)
Sparse
^^^^^^
- Bug in :meth:`SparseArray.take` when using a different fill value than the array's fill value (:issue:`55181`)
--
-
-ExtensionArray
-^^^^^^^^^^^^^^
--
--
-
-Styler
-^^^^^^
--
--
Other
^^^^^
@@ -871,15 +843,11 @@ Other
- Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55009`)
- Bug in :meth:`DataFrame.from_dict` which would always sort the rows of the created :class:`DataFrame`. (:issue:`55683`)
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` raising a ``ValueError`` (:issue:`56478`)
-- Bug in rendering ``inf`` values inside a a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
+- Bug in rendering ``inf`` values inside a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
- Bug in rendering a :class:`Series` with a :class:`MultiIndex` when one of the index level's names is 0 not having that name displayed (:issue:`55415`)
- Bug in the error message when assigning an empty :class:`DataFrame` to a column (:issue:`55956`)
- Bug when time-like strings were being cast to :class:`ArrowDtype` with ``pyarrow.time64`` type (:issue:`56463`)
-.. ***DO NOT USE THIS SECTION***
-
--
--
.. ---------------------------------------------------------------------------
.. _whatsnew_220.contributors:
| Backport PR #56632: DOC: Minor fixups for 2.2.0 whatsnew | https://api.github.com/repos/pandas-dev/pandas/pulls/56640 | 2023-12-27T19:19:32Z | 2023-12-27T19:55:20Z | 2023-12-27T19:55:20Z | 2023-12-27T19:55:20Z |
Backport PR #56636 on branch 2.2.x (DOC: Fixup CoW userguide) | diff --git a/doc/source/user_guide/copy_on_write.rst b/doc/source/user_guide/copy_on_write.rst
index 050c3901c3420..a083297925007 100644
--- a/doc/source/user_guide/copy_on_write.rst
+++ b/doc/source/user_guide/copy_on_write.rst
@@ -317,7 +317,7 @@ you are modifying one object inplace.
.. ipython:: python
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
- df2 = df.reset_index()
+ df2 = df.reset_index(drop=True)
df2.iloc[0, 0] = 100
This creates two objects that share data and thus the setitem operation will trigger a
@@ -328,7 +328,7 @@ held by the object.
.. ipython:: python
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
- df = df.reset_index()
+ df = df.reset_index(drop=True)
df.iloc[0, 0] = 100
No copy is necessary in this example.
| Backport PR #56636: DOC: Fixup CoW userguide | https://api.github.com/repos/pandas-dev/pandas/pulls/56639 | 2023-12-27T19:03:55Z | 2023-12-27T19:43:09Z | 2023-12-27T19:43:09Z | 2023-12-27T19:43:09Z |
PERF: resolution, is_normalized | diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx
index 0a19092f57706..1e09874639d4f 100644
--- a/pandas/_libs/tslibs/vectorized.pyx
+++ b/pandas/_libs/tslibs/vectorized.pyx
@@ -234,7 +234,7 @@ def get_resolution(
for i in range(n):
# Analogous to: utc_val = stamps[i]
- utc_val = cnp.PyArray_GETITEM(stamps, cnp.PyArray_ITER_DATA(it))
+ utc_val = (<int64_t*>cnp.PyArray_ITER_DATA(it))[0]
if utc_val == NPY_NAT:
pass
@@ -331,7 +331,7 @@ def is_date_array_normalized(ndarray stamps, tzinfo tz, NPY_DATETIMEUNIT reso) -
for i in range(n):
# Analogous to: utc_val = stamps[i]
- utc_val = cnp.PyArray_GETITEM(stamps, cnp.PyArray_ITER_DATA(it))
+ utc_val = (<int64_t*>cnp.PyArray_ITER_DATA(it))[0]
local_val = info.utc_val_to_local_val(utc_val, &pos)
| ```
dti = pd.date_range("2016-01-01", periods=10_000)
dta = dti._data
In [4]: %timeit dta.is_normalized
354 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) # <- main
122 µs ± 2.71 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) # <- PR
In [5]: %timeit dta.resolution
493 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) # <- main
258 µs ± 10.3 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) # <- PR
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/56637 | 2023-12-27T17:31:47Z | 2023-12-27T18:52:01Z | 2023-12-27T18:52:01Z | 2023-12-27T23:43:38Z |
DOC: Fixup CoW userguide | diff --git a/doc/source/user_guide/copy_on_write.rst b/doc/source/user_guide/copy_on_write.rst
index 050c3901c3420..a083297925007 100644
--- a/doc/source/user_guide/copy_on_write.rst
+++ b/doc/source/user_guide/copy_on_write.rst
@@ -317,7 +317,7 @@ you are modifying one object inplace.
.. ipython:: python
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
- df2 = df.reset_index()
+ df2 = df.reset_index(drop=True)
df2.iloc[0, 0] = 100
This creates two objects that share data and thus the setitem operation will trigger a
@@ -328,7 +328,7 @@ held by the object.
.. ipython:: python
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
- df = df.reset_index()
+ df = df.reset_index(drop=True)
df.iloc[0, 0] = 100
No copy is necessary in this example.
| - [ ] closes #56622 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56636 | 2023-12-27T16:31:28Z | 2023-12-27T19:02:55Z | 2023-12-27T19:02:55Z | 2023-12-27T19:18:30Z |
CoW: Boolean indexer in MultiIndex raising read-only error | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5ee94b74c527e..38e82d43b3e92 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -773,6 +773,7 @@ Interval
Indexing
^^^^^^^^
+- Bug in :meth:`DataFrame.loc` mutating a boolean indexer when :class:`DataFrame` has a :class:`MultiIndex` (:issue:`56635`)
- Bug in :meth:`DataFrame.loc` when setting :class:`Series` with extension dtype into NumPy dtype (:issue:`55604`)
- Bug in :meth:`Index.difference` not returning a unique set of values when ``other`` is empty or ``other`` is considered non-comparable (:issue:`55113`)
- Bug in setting :class:`Categorical` values into a :class:`DataFrame` with numpy dtypes raising ``RecursionError`` (:issue:`52927`)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 2a4e027e2b806..02a841a2075fd 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3488,6 +3488,8 @@ def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]:
"is not the same length as the index"
)
lvl_indexer = np.asarray(k)
+ if indexer is None:
+ lvl_indexer = lvl_indexer.copy()
elif is_list_like(k):
# a collection of labels to include from this level (these are or'd)
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py
index 9afc98e558c11..91cd77741f79b 100644
--- a/pandas/tests/copy_view/test_indexing.py
+++ b/pandas/tests/copy_view/test_indexing.py
@@ -1180,6 +1180,27 @@ def test_series_midx_tuples_slice(using_copy_on_write, warn_copy_on_write):
tm.assert_series_equal(ser, expected)
+def test_midx_read_only_bool_indexer():
+ # GH#56635
+ def mklbl(prefix, n):
+ return [f"{prefix}{i}" for i in range(n)]
+
+ idx = pd.MultiIndex.from_product(
+ [mklbl("A", 4), mklbl("B", 2), mklbl("C", 4), mklbl("D", 2)]
+ )
+ cols = pd.MultiIndex.from_tuples(
+ [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"]
+ )
+ df = DataFrame(1, index=idx, columns=cols).sort_index().sort_index(axis=1)
+
+ mask = df[("a", "foo")] == 1
+ expected_mask = mask.copy()
+ result = df.loc[pd.IndexSlice[mask, :, ["C1", "C3"]], :]
+ expected = df.loc[pd.IndexSlice[:, :, ["C1", "C3"]], :]
+ tm.assert_frame_equal(result, expected)
+ tm.assert_series_equal(mask, expected_mask)
+
+
def test_loc_enlarging_with_dataframe(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3]})
rhs = DataFrame({"b": [1, 2, 3], "c": [4, 5, 6]})
| Found this while going through the docs | https://api.github.com/repos/pandas-dev/pandas/pulls/56635 | 2023-12-27T16:14:39Z | 2023-12-28T18:48:25Z | 2023-12-28T18:48:25Z | 2023-12-28T18:48:49Z |
DOC: Add whatsnew for 2.3.0 | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index ec024f36d78b1..09d1ae08df57a 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -10,6 +10,15 @@ This is the list of changes to pandas between each release. For full details,
see the `commit logs <https://github.com/pandas-dev/pandas/commits/>`_. For install and
upgrade instructions, see :ref:`install`.
+Version 2.3
+-----------
+
+.. toctree::
+ :maxdepth: 2
+
+ v2.3.0
+
+
Version 2.2
-----------
diff --git a/doc/source/whatsnew/v2.3.0.rst b/doc/source/whatsnew/v2.3.0.rst
new file mode 100644
index 0000000000000..1f1b0c7d7195a
--- /dev/null
+++ b/doc/source/whatsnew/v2.3.0.rst
@@ -0,0 +1,219 @@
+.. _whatsnew_230:
+
+What's new in 2.3.0 (Month XX, 2024)
+------------------------------------
+
+These are the changes in pandas 2.2.0. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.enhancements:
+
+Enhancements
+~~~~~~~~~~~~
+
+.. _whatsnew_230.enhancements.enhancement1:
+
+enhancement1
+^^^^^^^^^^^^
+
+.. _whatsnew_230.enhancements.enhancement2:
+
+enhancement2
+^^^^^^^^^^^^
+
+.. _whatsnew_230.enhancements.other:
+
+Other enhancements
+^^^^^^^^^^^^^^^^^^
+-
+-
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.notable_bug_fixes:
+
+Notable bug fixes
+~~~~~~~~~~~~~~~~~
+
+These are bug fixes that might have notable behavior changes.
+
+.. _whatsnew_230.notable_bug_fixes.notable_bug_fix1:
+
+notable_bug_fix1
+^^^^^^^^^^^^^^^^
+
+.. _whatsnew_230.notable_bug_fixes.notable_bug_fix2:
+
+notable_bug_fix2
+^^^^^^^^^^^^^^^^
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.api_breaking:
+
+Backwards incompatible API changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_230.api_breaking.deps:
+
+Increased minimum versions for dependencies
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Some minimum supported versions of dependencies were updated.
+If installed, we now require:
+
++-----------------+-----------------+----------+---------+
+| Package | Minimum Version | Required | Changed |
++=================+=================+==========+=========+
+| | | X | X |
++-----------------+-----------------+----------+---------+
+
+For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
+The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
+Optional libraries below the lowest tested version may still work, but are not considered supported.
+
++-----------------+---------------------+
+| Package | New Minimum Version |
++=================+=====================+
+| | |
++-----------------+---------------------+
+
+See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
+
+.. _whatsnew_230.api_breaking.other:
+
+Other API changes
+^^^^^^^^^^^^^^^^^
+-
+-
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.deprecations:
+
+Deprecations
+~~~~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.performance:
+
+Performance improvements
+~~~~~~~~~~~~~~~~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+
+Categorical
+^^^^^^^^^^^
+-
+-
+
+Datetimelike
+^^^^^^^^^^^^
+-
+-
+
+Timedelta
+^^^^^^^^^
+-
+-
+
+Timezones
+^^^^^^^^^
+-
+-
+
+Numeric
+^^^^^^^
+-
+-
+
+Conversion
+^^^^^^^^^^
+-
+-
+
+Strings
+^^^^^^^
+-
+-
+
+Interval
+^^^^^^^^
+-
+-
+
+Indexing
+^^^^^^^^
+-
+-
+
+Missing
+^^^^^^^
+-
+-
+
+MultiIndex
+^^^^^^^^^^
+-
+-
+
+I/O
+^^^
+-
+-
+
+Period
+^^^^^^
+-
+-
+
+Plotting
+^^^^^^^^
+-
+-
+
+Groupby/resample/rolling
+^^^^^^^^^^^^^^^^^^^^^^^^
+-
+-
+
+Reshaping
+^^^^^^^^^
+-
+-
+
+Sparse
+^^^^^^
+-
+-
+
+ExtensionArray
+^^^^^^^^^^^^^^
+-
+-
+
+Styler
+^^^^^^
+-
+-
+
+Other
+^^^^^
+
+.. ***DO NOT USE THIS SECTION***
+
+-
+-
+
+.. ---------------------------------------------------------------------------
+.. _whatsnew_230.contributors:
+
+Contributors
+~~~~~~~~~~~~
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56634 | 2023-12-27T16:06:11Z | 2023-12-28T16:25:57Z | 2023-12-28T16:25:57Z | 2024-01-11T00:05:18Z |
CoW: Enable CoW by default and remove warning build | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index a3cffb4b03b93..2b09aa9343b79 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -73,18 +73,6 @@ jobs:
env_file: actions-312.yaml
pattern: "not slow and not network and not single_cpu"
pandas_copy_on_write: "1"
- - name: "Copy-on-Write 3.11 (warnings)"
- env_file: actions-311.yaml
- pattern: "not slow and not network and not single_cpu"
- pandas_copy_on_write: "warn"
- - name: "Copy-on-Write 3.10 (warnings)"
- env_file: actions-310.yaml
- pattern: "not slow and not network and not single_cpu"
- pandas_copy_on_write: "warn"
- - name: "Copy-on-Write 3.9 (warnings)"
- env_file: actions-39.yaml
- pattern: "not slow and not network and not single_cpu"
- pandas_copy_on_write: "warn"
- name: "Pypy"
env_file: actions-pypy-39.yaml
pattern: "not slow and not network and not single_cpu"
diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py
index f9ea3d5684751..a17732c70c2c7 100644
--- a/asv_bench/benchmarks/algos/isin.py
+++ b/asv_bench/benchmarks/algos/isin.py
@@ -59,7 +59,8 @@ def setup(self, dtype):
elif dtype in ["str", "string[python]", "string[pyarrow]"]:
try:
self.series = Series(
- Index([f"i-{i}" for i in range(N)], dtype=object), dtype=dtype
+ Index([f"i-{i}" for i in range(N)], dtype=object)._values,
+ dtype=dtype,
)
except ImportError as err:
raise NotImplementedError from err
diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index e6842fbc13f46..467fab857d306 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -19,7 +19,8 @@ class Dtypes:
def setup(self, dtype):
try:
self.s = Series(
- Index([f"i-{i}" for i in range(10000)], dtype=object), dtype=dtype
+ Index([f"i-{i}" for i in range(10000)], dtype=object)._values,
+ dtype=dtype,
)
except ImportError as err:
raise NotImplementedError from err
diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py
index 5b2bac2e8d747..0594d1c190a72 100644
--- a/pandas/_config/__init__.py
+++ b/pandas/_config/__init__.py
@@ -32,13 +32,11 @@
def using_copy_on_write() -> bool:
- _mode_options = _global_config["mode"]
- return _mode_options["copy_on_write"] is True
+ return True
def warn_copy_on_write() -> bool:
- _mode_options = _global_config["mode"]
- return _mode_options["copy_on_write"] == "warn"
+ return False
def using_nullable_dtypes() -> bool:
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 26e03ca30d4fb..db251a07aeb5d 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1963,7 +1963,7 @@ def using_copy_on_write() -> bool:
"""
Fixture to check if Copy-on-Write is enabled.
"""
- return pd.options.mode.copy_on_write is True
+ return True
@pytest.fixture
@@ -1971,7 +1971,7 @@ def warn_copy_on_write() -> bool:
"""
Fixture to check if Copy-on-Write is in warning mode.
"""
- return pd.options.mode.copy_on_write == "warn"
+ return False
@pytest.fixture
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 037f809eaabca..73f9481e53dea 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6704,8 +6704,7 @@ def copy(self, deep: bool_t | None = True) -> Self:
:ref:`gotchas <gotchas.thread-safety>` when copying in a threading
environment.
- When ``copy_on_write`` in pandas config is set to ``True``, the
- ``copy_on_write`` config takes effect even when ``deep=False``.
+ Copy-on-Write protects shallow copies against accidental modifications.
This means that any changes to the copied data would make a new copy
of the data upon write (and vice versa). Changes made to either the
original or copied variable would not be reflected in the counterpart.
@@ -6731,12 +6730,15 @@ def copy(self, deep: bool_t | None = True) -> Self:
>>> deep = s.copy()
>>> shallow = s.copy(deep=False)
- Shallow copy shares data and index with original.
+ Shallow copy shares index with original, the data is a
+ view of the original.
>>> s is shallow
False
- >>> s.values is shallow.values and s.index is shallow.index
- True
+ >>> s.values is shallow.values
+ False
+ >>> s.index is shallow.index
+ False
Deep copy has own copy of data and index.
@@ -6745,18 +6747,17 @@ def copy(self, deep: bool_t | None = True) -> Self:
>>> s.values is deep.values or s.index is deep.index
False
- Updates to the data shared by shallow copy and original is reflected
- in both (NOTE: this will no longer be true for pandas >= 3.0);
- deep copy remains unchanged.
+ The shallow copy is protected against updating the original object
+ as well. Thus, updates will only reflect in one of both objects.
>>> s.iloc[0] = 3
>>> shallow.iloc[1] = 4
>>> s
a 3
- b 4
+ b 2
dtype: int64
>>> shallow
- a 3
+ a 1
b 4
dtype: int64
>>> deep
@@ -6779,22 +6780,6 @@ def copy(self, deep: bool_t | None = True) -> Self:
0 [10, 2]
1 [3, 4]
dtype: object
-
- **Copy-on-Write is set to true**, the shallow copy is not modified
- when the original data is changed:
-
- >>> with pd.option_context("mode.copy_on_write", True):
- ... s = pd.Series([1, 2], index=["a", "b"])
- ... copy = s.copy(deep=False)
- ... s.iloc[0] = 100
- ... s
- a 100
- b 2
- dtype: int64
- >>> copy
- a 1
- b 2
- dtype: int64
"""
data = self._mgr.copy(deep=deep)
self._clear_item_cache()
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index a80ee421a1b8a..0495f23508c09 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3492,6 +3492,8 @@ def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]:
"cannot index with a boolean indexer that "
"is not the same length as the index"
)
+ if isinstance(k, (ABCSeries, Index)):
+ k = k._values
lvl_indexer = np.asarray(k)
if indexer is None:
lvl_indexer = lvl_indexer.copy()
diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py
index 400fb8e03c18c..f1a4decce623f 100644
--- a/pandas/tests/copy_view/test_internals.py
+++ b/pandas/tests/copy_view/test_internals.py
@@ -1,7 +1,6 @@
import numpy as np
import pytest
-import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
@@ -42,35 +41,6 @@ def test_consolidate(using_copy_on_write):
assert df.loc[0, "b"] == 0.1
-@pytest.mark.single_cpu
-def test_switch_options():
- # ensure we can switch the value of the option within one session
- # (assuming data is constructed after switching)
-
- # using the option_context to ensure we set back to global option value
- # after running the test
- with pd.option_context("mode.copy_on_write", False):
- df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
- subset = df[:]
- subset.iloc[0, 0] = 0
- # df updated with CoW disabled
- assert df.iloc[0, 0] == 0
-
- pd.options.mode.copy_on_write = True
- df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
- subset = df[:]
- subset.iloc[0, 0] = 0
- # df not updated with CoW enabled
- assert df.iloc[0, 0] == 1
-
- pd.options.mode.copy_on_write = False
- df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
- subset = df[:]
- subset.iloc[0, 0] = 0
- # df updated with CoW disabled
- assert df.iloc[0, 0] == 0
-
-
@pytest.mark.parametrize("dtype", [np.intp, np.int8])
@pytest.mark.parametrize(
"locs, arr",
diff --git a/pandas/tests/extension/conftest.py b/pandas/tests/extension/conftest.py
index 77f1dd2a8e49c..3a3844d5a8b7a 100644
--- a/pandas/tests/extension/conftest.py
+++ b/pandas/tests/extension/conftest.py
@@ -2,10 +2,7 @@
import pytest
-from pandas import (
- Series,
- options,
-)
+from pandas import Series
@pytest.fixture
@@ -222,4 +219,4 @@ def using_copy_on_write() -> bool:
"""
Fixture to check if Copy-on-Write is enabled.
"""
- return options.mode.copy_on_write is True
+ return True
diff --git a/pandas/tests/frame/methods/test_copy.py b/pandas/tests/frame/methods/test_copy.py
index 6208d0256a655..5b72a84320c52 100644
--- a/pandas/tests/frame/methods/test_copy.py
+++ b/pandas/tests/frame/methods/test_copy.py
@@ -1,10 +1,7 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import DataFrame
-import pandas._testing as tm
class TestCopy:
@@ -18,25 +15,6 @@ def test_copy_index_name_checking(self, float_frame, attr):
getattr(cp, attr).name = "foo"
assert getattr(float_frame, attr).name is None
- @td.skip_copy_on_write_invalid_test
- def test_copy_cache(self):
- # GH#31784 _item_cache not cleared on copy causes incorrect reads after updates
- df = DataFrame({"a": [1]})
-
- df["x"] = [0]
- df["a"]
-
- df.copy()
-
- df["a"].values[0] = -1
-
- tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]}))
-
- df["y"] = [0]
-
- assert df["a"].values[0] == -1
- tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))
-
def test_copy(self, float_frame, float_string_frame):
cop = float_frame.copy()
cop["E"] = cop["A"]
diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py
index 3ef319174313d..94a6910509e2d 100644
--- a/pandas/tests/series/test_ufunc.py
+++ b/pandas/tests/series/test_ufunc.py
@@ -5,8 +5,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
import pandas._testing as tm
from pandas.arrays import SparseArray
@@ -456,8 +454,7 @@ def add3(x, y, z):
ufunc(ser, ser, df)
-# TODO(CoW) see https://github.com/pandas-dev/pandas/pull/51082
-@td.skip_copy_on_write_not_yet_implemented
+@pytest.mark.xfail(reason="see https://github.com/pandas-dev/pandas/pull/51082")
def test_np_fix():
# np.fix is not a ufunc but is composed of several ufunc calls under the hood
# with `out` and `where` keywords
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 10776fe5d050f..feba0e86c6b32 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -58,8 +58,8 @@ def test_dask_ufunc():
s = Series([1.5, 2.3, 3.7, 4.0])
ds = dd.from_pandas(s, npartitions=2)
- result = da.fix(ds).compute()
- expected = np.fix(s)
+ result = da.log(ds).compute()
+ expected = np.log(s)
tm.assert_series_equal(result, expected)
finally:
pd.set_option("compute.use_numexpr", olduse)
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 37908c9ac255b..78626781289c4 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -33,12 +33,9 @@ def test_foo():
import pytest
-from pandas._config import get_option
-
if TYPE_CHECKING:
from pandas._typing import F
-
from pandas.compat import (
IS64,
is_platform_windows,
@@ -144,14 +141,3 @@ def documented_fixture(fixture):
return fixture
return documented_fixture
-
-
-skip_copy_on_write_not_yet_implemented = pytest.mark.xfail(
- get_option("mode.copy_on_write") is True,
- reason="Not yet implemented/adapted for Copy-on-Write mode",
-)
-
-skip_copy_on_write_invalid_test = pytest.mark.skipif(
- get_option("mode.copy_on_write") is True,
- reason="Test not valid for Copy-on-Write mode",
-)
| I'd prefer to go this way in enabling CoW. Having it on makes it easier to enforce the change step by step rather than doing it all at once. | https://api.github.com/repos/pandas-dev/pandas/pulls/56633 | 2023-12-27T15:50:11Z | 2024-02-01T09:04:05Z | 2024-02-01T09:04:05Z | 2024-02-01T09:04:09Z |
DOC: Minor fixups for 2.2.0 whatsnew | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5ee94b74c527e..5b955aa45219a 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -123,7 +123,7 @@ nullability handling.
with pg_dbapi.connect(uri) as conn:
df.to_sql("pandas_table", conn, index=False)
- # for roundtripping
+ # for round-tripping
with pg_dbapi.connect(uri) as conn:
df2 = pd.read_sql("pandas_table", conn)
@@ -176,7 +176,7 @@ leverage the ``dtype_backend="pyarrow"`` argument of :func:`~pandas.read_sql`
.. code-block:: ipython
- # for roundtripping
+ # for round-tripping
with pg_dbapi.connect(uri) as conn:
df2 = pd.read_sql("pandas_table", conn, dtype_backend="pyarrow")
@@ -306,22 +306,21 @@ Other enhancements
- :meth:`~DataFrame.to_sql` with method parameter set to ``multi`` works with Oracle on the backend
- :attr:`Series.attrs` / :attr:`DataFrame.attrs` now uses a deepcopy for propagating ``attrs`` (:issue:`54134`).
- :func:`get_dummies` now returning extension dtypes ``boolean`` or ``bool[pyarrow]`` that are compatible with the input dtype (:issue:`56273`)
-- :func:`read_csv` now supports ``on_bad_lines`` parameter with ``engine="pyarrow"``. (:issue:`54480`)
+- :func:`read_csv` now supports ``on_bad_lines`` parameter with ``engine="pyarrow"`` (:issue:`54480`)
- :func:`read_sas` returns ``datetime64`` dtypes with resolutions better matching those stored natively in SAS, and avoids returning object-dtype in cases that cannot be stored with ``datetime64[ns]`` dtype (:issue:`56127`)
-- :func:`read_spss` now returns a :class:`DataFrame` that stores the metadata in :attr:`DataFrame.attrs`. (:issue:`54264`)
+- :func:`read_spss` now returns a :class:`DataFrame` that stores the metadata in :attr:`DataFrame.attrs` (:issue:`54264`)
- :func:`tseries.api.guess_datetime_format` is now part of the public API (:issue:`54727`)
+- :meth:`DataFrame.apply` now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- :meth:`ExtensionArray._explode` interface method added to allow extension type implementations of the ``explode`` method (:issue:`54833`)
- :meth:`ExtensionArray.duplicated` added to allow extension type implementations of the ``duplicated`` method (:issue:`55255`)
- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
-- DataFrame.apply now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
- Implemented :meth:`Series.str.extract` for :class:`ArrowDtype` (:issue:`56268`)
-- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as "BMS" (:issue:`56243`)
-- Improved error message when constructing :class:`Period` with invalid offsets such as "QS" (:issue:`55785`)
+- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as ``"BMS"`` (:issue:`56243`)
+- Improved error message when constructing :class:`Period` with invalid offsets such as ``"QS"`` (:issue:`55785`)
- The dtypes ``string[pyarrow]`` and ``string[pyarrow_numpy]`` now both utilize the ``large_string`` type from PyArrow to avoid overflow for long columns (:issue:`56259`)
-
.. ---------------------------------------------------------------------------
.. _whatsnew_220.notable_bug_fixes:
@@ -386,6 +385,8 @@ index levels when joining on two indexes with different levels (:issue:`34133`).
left = pd.DataFrame({"left": 1}, index=pd.MultiIndex.from_tuples([("x", 1), ("x", 2)], names=["A", "B"]))
right = pd.DataFrame({"right": 2}, index=pd.MultiIndex.from_tuples([(1, 1), (2, 2)], names=["B", "C"]))
+ left
+ right
result = left.join(right)
*Old Behavior*
@@ -415,15 +416,6 @@ Backwards incompatible API changes
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Some minimum supported versions of dependencies were updated.
-If installed, we now require:
-
-+-----------------+-----------------+----------+---------+
-| Package | Minimum Version | Required | Changed |
-+=================+=================+==========+=========+
-| | | X | X |
-+-----------------+-----------------+----------+---------+
-
For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
Optional libraries below the lowest tested version may still work, but are not considered supported.
@@ -433,8 +425,6 @@ Optional libraries below the lowest tested version may still work, but are not c
+=================+=================+=========+
| mypy (dev) | 1.8.0 | X |
+-----------------+-----------------+---------+
-| | | X |
-+-----------------+-----------------+---------+
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
@@ -606,20 +596,20 @@ Other Deprecations
- Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`)
- Deprecated accepting a type as an argument in :meth:`Index.view`, call without any arguments instead (:issue:`55709`)
- Deprecated allowing non-integer ``periods`` argument in :func:`date_range`, :func:`timedelta_range`, :func:`period_range`, and :func:`interval_range` (:issue:`56036`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard`. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict`. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_excel` except ``excel_writer``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_gbq` except ``destination_table``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_hdf` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_html` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_json` except ``path_or_buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_latex` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_markdown` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_parquet` except ``path``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf``. (:issue:`54229`)
-- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_xml` except ``path_or_buffer``. (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_excel` except ``excel_writer`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_gbq` except ``destination_table`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_hdf` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_html` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_json` except ``path_or_buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_latex` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_markdown` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_parquet` except ``path`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf`` (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_xml` except ``path_or_buffer`` (:issue:`54229`)
- Deprecated allowing passing :class:`BlockManager` objects to :class:`DataFrame` or :class:`SingleBlockManager` objects to :class:`Series` (:issue:`52419`)
- Deprecated behavior of :meth:`Index.insert` with an object-dtype index silently performing type inference on the result, explicitly call ``result.infer_objects(copy=False)`` for the old behavior instead (:issue:`51363`)
- Deprecated casting non-datetimelike values (mainly strings) in :meth:`Series.isin` and :meth:`Index.isin` with ``datetime64``, ``timedelta64``, and :class:`PeriodDtype` dtypes (:issue:`53111`)
@@ -692,31 +682,30 @@ Bug fixes
Categorical
^^^^^^^^^^^
- :meth:`Categorical.isin` raising ``InvalidIndexError`` for categorical containing overlapping :class:`Interval` values (:issue:`34974`)
-- Bug in :meth:`CategoricalDtype.__eq__` returning false for unordered categorical data with mixed types (:issue:`55468`)
--
+- Bug in :meth:`CategoricalDtype.__eq__` returning ``False`` for unordered categorical data with mixed types (:issue:`55468`)
Datetimelike
^^^^^^^^^^^^
- Bug in :class:`DatetimeIndex` construction when passing both a ``tz`` and either ``dayfirst`` or ``yearfirst`` ignoring dayfirst/yearfirst (:issue:`55813`)
- Bug in :class:`DatetimeIndex` when passing an object-dtype ndarray of float objects and a ``tz`` incorrectly localizing the result (:issue:`55780`)
- Bug in :func:`Series.isin` with :class:`DatetimeTZDtype` dtype and comparison values that are all ``NaT`` incorrectly returning all-``False`` even if the series contains ``NaT`` entries (:issue:`56427`)
-- Bug in :func:`concat` raising ``AttributeError`` when concatenating all-NA DataFrame with :class:`DatetimeTZDtype` dtype DataFrame. (:issue:`52093`)
+- Bug in :func:`concat` raising ``AttributeError`` when concatenating all-NA DataFrame with :class:`DatetimeTZDtype` dtype DataFrame (:issue:`52093`)
- Bug in :func:`testing.assert_extension_array_equal` that could use the wrong unit when comparing resolutions (:issue:`55730`)
- Bug in :func:`to_datetime` and :class:`DatetimeIndex` when passing a list of mixed-string-and-numeric types incorrectly raising (:issue:`55780`)
- Bug in :func:`to_datetime` and :class:`DatetimeIndex` when passing mixed-type objects with a mix of timezones or mix of timezone-awareness failing to raise ``ValueError`` (:issue:`55693`)
+- Bug in :meth:`.Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in :meth:`DatetimeIndex.shift` with non-nanosecond resolution incorrectly returning with nanosecond resolution (:issue:`56117`)
- Bug in :meth:`DatetimeIndex.union` returning object dtype for tz-aware indexes with the same timezone but different units (:issue:`55238`)
- Bug in :meth:`Index.is_monotonic_increasing` and :meth:`Index.is_monotonic_decreasing` always caching :meth:`Index.is_unique` as ``True`` when first value in index is ``NaT`` (:issue:`55755`)
- Bug in :meth:`Index.view` to a datetime64 dtype with non-supported resolution incorrectly raising (:issue:`55710`)
- Bug in :meth:`Series.dt.round` with non-nanosecond resolution and ``NaT`` entries incorrectly raising ``OverflowError`` (:issue:`56158`)
- Bug in :meth:`Series.fillna` with non-nanosecond resolution dtypes and higher-resolution vector values returning incorrect (internally-corrupted) results (:issue:`56410`)
-- Bug in :meth:`Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in :meth:`Timestamp.unit` being inferred incorrectly from an ISO8601 format string with minute or hour resolution and a timezone offset (:issue:`56208`)
-- Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetim64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`)
+- Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetime64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`)
- Bug in adding or subtracting a :class:`Week` offset to a ``datetime64`` :class:`Series`, :class:`Index`, or :class:`DataFrame` column with non-nanosecond resolution returning incorrect results (:issue:`55583`)
- Bug in addition or subtraction of :class:`BusinessDay` offset with ``offset`` attribute to non-nanosecond :class:`Index`, :class:`Series`, or :class:`DataFrame` column giving incorrect results (:issue:`55608`)
- Bug in addition or subtraction of :class:`DateOffset` objects with microsecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` columns with non-nanosecond resolution (:issue:`55595`)
-- Bug in addition or subtraction of very large :class:`Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
+- Bug in addition or subtraction of very large :class:`.Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond :class:`DatetimeTZDtype` and inputs that would be out of bounds with nanosecond resolution incorrectly raising ``OutOfBoundsDatetime`` (:issue:`54620`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` (or :class:`DatetimeTZDtype`) from mixed-numeric inputs treating those as nanoseconds instead of as multiples of the dtype's unit (which would happen with non-mixed numeric inputs) (:issue:`56004`)
- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` dtype and inputs that would be out of bounds for a ``datetime64[ns]`` incorrectly raising ``OutOfBoundsDatetime`` (:issue:`55756`)
@@ -739,14 +728,12 @@ Numeric
^^^^^^^
- Bug in :func:`read_csv` with ``engine="pyarrow"`` causing rounding errors for large integers (:issue:`52505`)
- Bug in :meth:`Series.pow` not filling missing values correctly (:issue:`55512`)
--
Conversion
^^^^^^^^^^
- Bug in :meth:`DataFrame.astype` when called with ``str`` on unpickled array - the array might change in-place (:issue:`54654`)
- Bug in :meth:`DataFrame.astype` where ``errors="ignore"`` had no effect for extension types (:issue:`54654`)
- Bug in :meth:`Series.convert_dtypes` not converting all NA column to ``null[pyarrow]`` (:issue:`55346`)
--
Strings
^^^^^^^
@@ -763,13 +750,12 @@ Strings
Interval
^^^^^^^^
-- Bug in :class:`Interval` ``__repr__`` not displaying UTC offsets for :class:`Timestamp` bounds. Additionally the hour, minute and second components will now be shown. (:issue:`55015`)
+- Bug in :class:`Interval` ``__repr__`` not displaying UTC offsets for :class:`Timestamp` bounds. Additionally the hour, minute and second components will now be shown (:issue:`55015`)
- Bug in :meth:`IntervalIndex.factorize` and :meth:`Series.factorize` with :class:`IntervalDtype` with datetime64 or timedelta64 intervals not preserving non-nanosecond units (:issue:`56099`)
- Bug in :meth:`IntervalIndex.from_arrays` when passed ``datetime64`` or ``timedelta64`` arrays with mismatched resolutions constructing an invalid ``IntervalArray`` object (:issue:`55714`)
- Bug in :meth:`IntervalIndex.get_indexer` with datetime or timedelta intervals incorrectly matching on integer targets (:issue:`47772`)
- Bug in :meth:`IntervalIndex.get_indexer` with timezone-aware datetime intervals incorrectly matching on a sequence of timezone-naive targets (:issue:`47772`)
- Bug in setting values on a :class:`Series` with an :class:`IntervalIndex` using a slice incorrectly raising (:issue:`54722`)
--
Indexing
^^^^^^^^
@@ -781,25 +767,23 @@ Indexing
Missing
^^^^^^^
- Bug in :meth:`DataFrame.update` wasn't updating in-place for tz-aware datetime64 dtypes (:issue:`56227`)
--
MultiIndex
^^^^^^^^^^
- Bug in :meth:`MultiIndex.get_indexer` not raising ``ValueError`` when ``method`` provided and index is non-monotonic (:issue:`53452`)
--
I/O
^^^
-- Bug in :func:`read_csv` where ``engine="python"`` did not respect ``chunksize`` arg when ``skiprows`` was specified. (:issue:`56323`)
-- Bug in :func:`read_csv` where ``engine="python"`` was causing a ``TypeError`` when a callable ``skiprows`` and a chunk size was specified. (:issue:`55677`)
-- Bug in :func:`read_csv` where ``on_bad_lines="warn"`` would write to ``stderr`` instead of raise a Python warning. This now yields a :class:`.errors.ParserWarning` (:issue:`54296`)
+- Bug in :func:`read_csv` where ``engine="python"`` did not respect ``chunksize`` arg when ``skiprows`` was specified (:issue:`56323`)
+- Bug in :func:`read_csv` where ``engine="python"`` was causing a ``TypeError`` when a callable ``skiprows`` and a chunk size was specified (:issue:`55677`)
+- Bug in :func:`read_csv` where ``on_bad_lines="warn"`` would write to ``stderr`` instead of raising a Python warning; this now yields a :class:`.errors.ParserWarning` (:issue:`54296`)
- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``quotechar`` was ignored (:issue:`52266`)
-- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``usecols`` wasn't working with a csv with no headers (:issue:`54459`)
-- Bug in :func:`read_excel`, with ``engine="xlrd"`` (``xls`` files) erroring when file contains NaNs/Infs (:issue:`54564`)
+- Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``usecols`` wasn't working with a CSV with no headers (:issue:`54459`)
+- Bug in :func:`read_excel`, with ``engine="xlrd"`` (``xls`` files) erroring when the file contains ``NaN`` or ``Inf`` (:issue:`54564`)
- Bug in :func:`read_json` not handling dtype conversion properly if ``infer_string`` is set (:issue:`56195`)
-- Bug in :meth:`DataFrame.to_excel`, with ``OdsWriter`` (``ods`` files) writing boolean/string value (:issue:`54994`)
+- Bug in :meth:`DataFrame.to_excel`, with ``OdsWriter`` (``ods`` files) writing Boolean/string value (:issue:`54994`)
- Bug in :meth:`DataFrame.to_hdf` and :func:`read_hdf` with ``datetime64`` dtypes with non-nanosecond resolution failing to round-trip correctly (:issue:`55622`)
-- Bug in :meth:`~pandas.read_excel` with ``engine="odf"`` (``ods`` files) when string contains annotation (:issue:`55200`)
+- Bug in :meth:`~pandas.read_excel` with ``engine="odf"`` (``ods`` files) when a string cell contains an annotation (:issue:`55200`)
- Bug in :meth:`~pandas.read_excel` with an ODS file without cached formatted cell for float values (:issue:`55219`)
- Bug where :meth:`DataFrame.to_json` would raise an ``OverflowError`` instead of a ``TypeError`` with unsupported NumPy types (:issue:`55403`)
@@ -808,12 +792,11 @@ Period
- Bug in :class:`PeriodIndex` construction when more than one of ``data``, ``ordinal`` and ``**fields`` are passed failing to raise ``ValueError`` (:issue:`55961`)
- Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`)
- Bug in casting from :class:`PeriodDtype` with ``astype`` to ``datetime64`` or :class:`DatetimeTZDtype` with non-nanosecond unit incorrectly returning with nanosecond unit (:issue:`55958`)
--
Plotting
^^^^^^^^
-- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
-- Bug in :meth:`DataFrame.plot.scatter` discaring string columns (:issue:`56142`)
+- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a Matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
+- Bug in :meth:`DataFrame.plot.scatter` discarding string columns (:issue:`56142`)
- Bug in :meth:`Series.plot` when reusing an ``ax`` object failing to raise when a ``how`` keyword is passed (:issue:`55953`)
Groupby/resample/rolling
@@ -821,9 +804,9 @@ Groupby/resample/rolling
- Bug in :class:`.Rolling` where duplicate datetimelike indexes are treated as consecutive rather than equal with ``closed='left'`` and ``closed='neither'`` (:issue:`20712`)
- Bug in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, and :meth:`.SeriesGroupBy.idxmax` would not retain :class:`.Categorical` dtype when the index was a :class:`.CategoricalIndex` that contained NA values (:issue:`54234`)
- Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.SeriesGroupBy.transform` when ``observed=False`` and ``f="idxmin"`` or ``f="idxmax"`` would incorrectly raise on unobserved categories (:issue:`54234`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`55951`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`55951`)
-- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_count` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`55951`)
+- Bug in :meth:`.DataFrameGroupBy.value_counts` and :meth:`.SeriesGroupBy.value_counts` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`55951`)
- Bug in :meth:`DataFrame.asfreq` and :meth:`Series.asfreq` with a :class:`DatetimeIndex` with non-nanosecond resolution incorrectly converting to nanosecond resolution (:issue:`55958`)
- Bug in :meth:`DataFrame.ewm` when passed ``times`` with non-nanosecond ``datetime64`` or :class:`DatetimeTZDtype` dtype (:issue:`56262`)
- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` where grouping by a combination of ``Decimal`` and NA values would fail when ``sort=True`` (:issue:`54847`)
@@ -845,22 +828,11 @@ Reshaping
- Bug in :meth:`DataFrame.melt` where it would not preserve the datetime (:issue:`55254`)
- Bug in :meth:`DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`)
- Bug in :meth:`DataFrame.pivot` with numeric columns and extension dtype for data (:issue:`56528`)
-- Bug in :meth:`DataFrame.stack` and :meth:`Series.stack` with ``future_stack=True`` would not preserve NA values in the index (:issue:`56573`)
+- Bug in :meth:`DataFrame.stack` with ``future_stack=True`` would not preserve NA values in the index (:issue:`56573`)
Sparse
^^^^^^
- Bug in :meth:`SparseArray.take` when using a different fill value than the array's fill value (:issue:`55181`)
--
-
-ExtensionArray
-^^^^^^^^^^^^^^
--
--
-
-Styler
-^^^^^^
--
--
Other
^^^^^
@@ -871,15 +843,11 @@ Other
- Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55009`)
- Bug in :meth:`DataFrame.from_dict` which would always sort the rows of the created :class:`DataFrame`. (:issue:`55683`)
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` raising a ``ValueError`` (:issue:`56478`)
-- Bug in rendering ``inf`` values inside a a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
+- Bug in rendering ``inf`` values inside a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
- Bug in rendering a :class:`Series` with a :class:`MultiIndex` when one of the index level's names is 0 not having that name displayed (:issue:`55415`)
- Bug in the error message when assigning an empty :class:`DataFrame` to a column (:issue:`55956`)
- Bug when time-like strings were being cast to :class:`ArrowDtype` with ``pyarrow.time64`` type (:issue:`56463`)
-.. ***DO NOT USE THIS SECTION***
-
--
--
.. ---------------------------------------------------------------------------
.. _whatsnew_220.contributors:
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56632 | 2023-12-27T14:50:41Z | 2023-12-27T19:19:25Z | 2023-12-27T19:19:25Z | 2023-12-27T19:36:08Z |
TYP: more simple return types from ruff | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 25a71ce5b5f4f..784e11415ade6 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -827,7 +827,7 @@ def generate_numba_apply_func(
def apply_with_numba(self):
pass
- def validate_values_for_numba(self):
+ def validate_values_for_numba(self) -> None:
# Validate column dtyps all OK
for colname, dtype in self.obj.dtypes.items():
if not is_numeric_dtype(dtype):
diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py
index 5f377276be480..60fc172139f13 100644
--- a/pandas/core/array_algos/replace.py
+++ b/pandas/core/array_algos/replace.py
@@ -67,7 +67,7 @@ def compare_or_regex_search(
def _check_comparison_types(
result: ArrayLike | bool, a: ArrayLike, b: Scalar | Pattern
- ):
+ ) -> None:
"""
Raises an error if the two arrays (a,b) cannot be compared.
Otherwise, returns the comparison result as expected.
diff --git a/pandas/core/arrays/arrow/accessors.py b/pandas/core/arrays/arrow/accessors.py
index 7f88267943526..23825faa70095 100644
--- a/pandas/core/arrays/arrow/accessors.py
+++ b/pandas/core/arrays/arrow/accessors.py
@@ -39,7 +39,7 @@ def __init__(self, data, validation_msg: str) -> None:
def _is_valid_pyarrow_dtype(self, pyarrow_dtype) -> bool:
pass
- def _validate(self, data):
+ def _validate(self, data) -> None:
dtype = data.dtype
if not isinstance(dtype, ArrowDtype):
# Raise AttributeError so that inspect can handle non-struct Series.
diff --git a/pandas/core/arrays/arrow/extension_types.py b/pandas/core/arrays/arrow/extension_types.py
index 72bfd6f2212f8..d52b60df47adc 100644
--- a/pandas/core/arrays/arrow/extension_types.py
+++ b/pandas/core/arrays/arrow/extension_types.py
@@ -135,7 +135,7 @@ def to_pandas_dtype(self) -> IntervalDtype:
"""
-def patch_pyarrow():
+def patch_pyarrow() -> None:
# starting from pyarrow 14.0.1, it has its own mechanism
if not pa_version_under14p1:
return
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 065a942cae768..8a88227ad54a3 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2164,7 +2164,9 @@ def __contains__(self, key) -> bool:
# ------------------------------------------------------------------
# Rendering Methods
- def _formatter(self, boxed: bool = False):
+ # error: Return type "None" of "_formatter" incompatible with return
+ # type "Callable[[Any], str | None]" in supertype "ExtensionArray"
+ def _formatter(self, boxed: bool = False) -> None: # type: ignore[override]
# Returning None here will cause format_array to do inference.
return None
@@ -2890,7 +2892,7 @@ def __init__(self, data) -> None:
self._freeze()
@staticmethod
- def _validate(data):
+ def _validate(data) -> None:
if not isinstance(data.dtype, CategoricalDtype):
raise AttributeError("Can only use .cat accessor with a 'category' dtype")
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 11a0c7bf18fcb..e04fcb84d51a0 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -2058,7 +2058,7 @@ def freq(self, value) -> None:
self._freq = value
@final
- def _maybe_pin_freq(self, freq, validate_kwds: dict):
+ def _maybe_pin_freq(self, freq, validate_kwds: dict) -> None:
"""
Constructor helper to pin the appropriate `freq` attribute. Assumes
that self._freq is currently set to any freq inferred in
@@ -2092,7 +2092,7 @@ def _maybe_pin_freq(self, freq, validate_kwds: dict):
@final
@classmethod
- def _validate_frequency(cls, index, freq: BaseOffset, **kwargs):
+ def _validate_frequency(cls, index, freq: BaseOffset, **kwargs) -> None:
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py
index fc7debb1f31e4..3dd7ebf564ca1 100644
--- a/pandas/core/arrays/sparse/accessor.py
+++ b/pandas/core/arrays/sparse/accessor.py
@@ -30,7 +30,7 @@ def __init__(self, data=None) -> None:
self._parent = data
self._validate(data)
- def _validate(self, data):
+ def _validate(self, data) -> None:
raise NotImplementedError
@@ -50,7 +50,7 @@ class SparseAccessor(BaseAccessor, PandasDelegate):
array([2, 2, 2])
"""
- def _validate(self, data):
+ def _validate(self, data) -> None:
if not isinstance(data.dtype, SparseDtype):
raise AttributeError(self._validation_msg)
@@ -243,7 +243,7 @@ class SparseFrameAccessor(BaseAccessor, PandasDelegate):
0.5
"""
- def _validate(self, data):
+ def _validate(self, data) -> None:
dtypes = data.dtypes
if not all(isinstance(t, SparseDtype) for t in dtypes):
raise AttributeError(self._validation_msg)
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 5db77db2a9c66..7a3ea85dde2b4 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -1830,7 +1830,9 @@ def __repr__(self) -> str:
pp_index = printing.pprint_thing(self.sp_index)
return f"{pp_str}\nFill: {pp_fill}\n{pp_index}"
- def _formatter(self, boxed: bool = False):
+ # error: Return type "None" of "_formatter" incompatible with return
+ # type "Callable[[Any], str | None]" in supertype "ExtensionArray"
+ def _formatter(self, boxed: bool = False) -> None: # type: ignore[override]
# Defer to the formatter from the GenericArrayFormatter calling us.
# This will infer the correct formatter from the dtype of the values.
return None
diff --git a/pandas/core/arrays/sparse/scipy_sparse.py b/pandas/core/arrays/sparse/scipy_sparse.py
index 71b71a9779da5..31e09c923d933 100644
--- a/pandas/core/arrays/sparse/scipy_sparse.py
+++ b/pandas/core/arrays/sparse/scipy_sparse.py
@@ -27,7 +27,7 @@
)
-def _check_is_partition(parts: Iterable, whole: Iterable):
+def _check_is_partition(parts: Iterable, whole: Iterable) -> None:
whole = set(whole)
parts = [set(x) for x in parts]
if set.intersection(*parts) != set():
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 00197a150fb97..f451ebc352733 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -364,7 +364,7 @@ def __init__(self, values, copy: bool = False) -> None:
self._validate()
NDArrayBacked.__init__(self, self._ndarray, StringDtype(storage="python"))
- def _validate(self):
+ def _validate(self) -> None:
"""Validate that we only store NA or strings."""
if len(self._ndarray) and not lib.is_string_array(self._ndarray, skipna=True):
raise ValueError("StringArray requires a sequence of strings or pandas.NA")
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index f1fe528de06f8..6313c2e2c98de 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -72,7 +72,7 @@ def _check_engine(engine: str | None) -> str:
return engine
-def _check_parser(parser: str):
+def _check_parser(parser: str) -> None:
"""
Make sure a valid parser is passed.
@@ -91,7 +91,7 @@ def _check_parser(parser: str):
)
-def _check_resolvers(resolvers):
+def _check_resolvers(resolvers) -> None:
if resolvers is not None:
for resolver in resolvers:
if not hasattr(resolver, "__getitem__"):
@@ -102,7 +102,7 @@ def _check_resolvers(resolvers):
)
-def _check_expression(expr):
+def _check_expression(expr) -> None:
"""
Make sure an expression is not an empty string
@@ -149,7 +149,7 @@ def _convert_expression(expr) -> str:
return s
-def _check_for_locals(expr: str, stack_level: int, parser: str):
+def _check_for_locals(expr: str, stack_level: int, parser: str) -> None:
at_top_of_stack = stack_level == 0
not_pandas_parser = parser != "pandas"
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py
index 95ac20ba39edc..9422434b5cde3 100644
--- a/pandas/core/computation/ops.py
+++ b/pandas/core/computation/ops.py
@@ -491,7 +491,7 @@ def stringify(value):
v = v.tz_convert("UTC")
self.lhs.update(v)
- def _disallow_scalar_only_bool_ops(self):
+ def _disallow_scalar_only_bool_ops(self) -> None:
rhs = self.rhs
lhs = self.lhs
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 7a088bf84c48e..72c33e95f68a0 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -231,7 +231,7 @@ def _maybe_unbox_datetimelike(value: Scalar, dtype: DtypeObj) -> Scalar:
return value
-def _disallow_mismatched_datetimelike(value, dtype: DtypeObj):
+def _disallow_mismatched_datetimelike(value, dtype: DtypeObj) -> None:
"""
numpy allows np.array(dt64values, dtype="timedelta64[ns]") and
vice-versa, but we do not want to allow this, so we need to
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 3e2e589440bd9..a46e42b9241ff 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4316,7 +4316,7 @@ def _setitem_array(self, key, value):
else:
self._iset_not_inplace(key, value)
- def _iset_not_inplace(self, key, value):
+ def _iset_not_inplace(self, key, value) -> None:
# GH#39510 when setting with df[key] = obj with a list-like key and
# list-like value, we iterate over those listlikes and set columns
# one at a time. This is different from dispatching to
@@ -4360,7 +4360,7 @@ def igetitem(obj, i: int):
finally:
self.columns = orig_columns
- def _setitem_frame(self, key, value):
+ def _setitem_frame(self, key, value) -> None:
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
if isinstance(key, np.ndarray):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index de25a02c6b37c..91a150c63c5b6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4394,7 +4394,7 @@ def _check_is_chained_assignment_possible(self) -> bool_t:
return False
@final
- def _check_setitem_copy(self, t: str = "setting", force: bool_t = False):
+ def _check_setitem_copy(self, t: str = "setting", force: bool_t = False) -> None:
"""
Parameters
@@ -4510,7 +4510,7 @@ def __delitem__(self, key) -> None:
# Unsorted
@final
- def _check_inplace_and_allows_duplicate_labels(self, inplace: bool_t):
+ def _check_inplace_and_allows_duplicate_labels(self, inplace: bool_t) -> None:
if inplace and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'inplace=True' when "
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 88a08dd55f739..d262dcd144d79 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3209,7 +3209,7 @@ def _get_reconciled_name_object(self, other):
return self
@final
- def _validate_sort_keyword(self, sort):
+ def _validate_sort_keyword(self, sort) -> None:
if sort not in [None, False, True]:
raise ValueError(
"The 'sort' keyword only takes the values of "
@@ -6051,7 +6051,7 @@ def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
# by RangeIndex, MultIIndex
return self._data.argsort(*args, **kwargs)
- def _check_indexing_error(self, key):
+ def _check_indexing_error(self, key) -> None:
if not is_scalar(key):
# if key is not a scalar, directly raise an error (the code below
# would convert to numpy arrays and raise later any way) - GH29926
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 2a4e027e2b806..56e3899eae6f6 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1571,7 +1571,7 @@ def _format_multi(
def _get_names(self) -> FrozenList:
return FrozenList(self._names)
- def _set_names(self, names, *, level=None, validate: bool = True):
+ def _set_names(self, names, *, level=None, validate: bool = True) -> None:
"""
Set new names on index. Each name has to be a hashable type.
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 4be7e17035128..a7dd3b486ab11 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -911,7 +911,7 @@ def __setitem__(self, key, value) -> None:
iloc = self if self.name == "iloc" else self.obj.iloc
iloc._setitem_with_indexer(indexer, value, self.name)
- def _validate_key(self, key, axis: AxisInt):
+ def _validate_key(self, key, axis: AxisInt) -> None:
"""
Ensure that key is valid for current indexer.
@@ -1225,7 +1225,7 @@ class _LocIndexer(_LocationIndexer):
# Key Checks
@doc(_LocationIndexer._validate_key)
- def _validate_key(self, key, axis: Axis):
+ def _validate_key(self, key, axis: Axis) -> None:
# valid for a collection of labels (we check their presence later)
# slice of labels (where start-end in labels)
# slice of integers (only if in the labels)
@@ -1572,7 +1572,7 @@ class _iLocIndexer(_LocationIndexer):
# -------------------------------------------------------------------
# Key Checks
- def _validate_key(self, key, axis: AxisInt):
+ def _validate_key(self, key, axis: AxisInt) -> None:
if com.is_bool_indexer(key):
if hasattr(key, "index") and isinstance(key.index, Index):
if key.index.inferred_type == "integer":
@@ -1783,7 +1783,7 @@ def _get_setitem_indexer(self, key):
# -------------------------------------------------------------------
- def _setitem_with_indexer(self, indexer, value, name: str = "iloc"):
+ def _setitem_with_indexer(self, indexer, value, name: str = "iloc") -> None:
"""
_setitem_with_indexer is for setting values on a Series/DataFrame
using positional indexers.
@@ -2038,7 +2038,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
for loc in ilocs:
self._setitem_single_column(loc, value, pi)
- def _setitem_with_indexer_2d_value(self, indexer, value):
+ def _setitem_with_indexer_2d_value(self, indexer, value) -> None:
# We get here with np.ndim(value) == 2, excluding DataFrame,
# which goes through _setitem_with_indexer_frame_value
pi = indexer[0]
@@ -2060,7 +2060,9 @@ def _setitem_with_indexer_2d_value(self, indexer, value):
value_col = value_col.tolist()
self._setitem_single_column(loc, value_col, pi)
- def _setitem_with_indexer_frame_value(self, indexer, value: DataFrame, name: str):
+ def _setitem_with_indexer_frame_value(
+ self, indexer, value: DataFrame, name: str
+ ) -> None:
ilocs = self._ensure_iterable_column_indexer(indexer[1])
sub_indexer = list(indexer)
diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py
index ae91f167205a0..8f16a6623c8cb 100644
--- a/pandas/core/internals/base.py
+++ b/pandas/core/internals/base.py
@@ -53,7 +53,7 @@
class _AlreadyWarned:
- def __init__(self):
+ def __init__(self) -> None:
# This class is used on the manager level to the block level to
# ensure that we warn only once. The block method can update the
# warned_already option without returning a value to keep the
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 3719bf1f77f85..5f38720135efa 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1940,13 +1940,15 @@ def _post_setstate(self) -> None:
def _block(self) -> Block:
return self.blocks[0]
+ # error: Cannot override writeable attribute with read-only property
@property
- def _blknos(self):
+ def _blknos(self) -> None: # type: ignore[override]
"""compat with BlockManager"""
return None
+ # error: Cannot override writeable attribute with read-only property
@property
- def _blklocs(self):
+ def _blklocs(self) -> None: # type: ignore[override]
"""compat with BlockManager"""
return None
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py
index 4b762a359d321..8ccd7c84cb05c 100644
--- a/pandas/core/ops/array_ops.py
+++ b/pandas/core/ops/array_ops.py
@@ -591,7 +591,7 @@ def maybe_prepare_scalar_for_op(obj, shape: Shape):
}
-def _bool_arith_check(op, a: np.ndarray, b):
+def _bool_arith_check(op, a: np.ndarray, b) -> None:
"""
In contrast to numpy, pandas raises an error for certain operations
with booleans.
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index aacea92611697..31859c7d04e04 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -765,7 +765,7 @@ def _get_concat_axis(self) -> Index:
return concat_axis
- def _maybe_check_integrity(self, concat_index: Index):
+ def _maybe_check_integrity(self, concat_index: Index) -> None:
if self.verify_integrity:
if not concat_index.is_unique:
overlap = concat_index[concat_index.duplicated()].unique()
diff --git a/pandas/core/reshape/encoding.py b/pandas/core/reshape/encoding.py
index 3ed67bb7b7c02..44158227d903b 100644
--- a/pandas/core/reshape/encoding.py
+++ b/pandas/core/reshape/encoding.py
@@ -169,7 +169,7 @@ def get_dummies(
data_to_encode = data[columns]
# validate prefixes and separator to avoid silently dropping cols
- def check_len(item, name: str):
+ def check_len(item, name: str) -> None:
if is_list_like(item):
if not len(item) == data_to_encode.shape[1]:
len_msg = (
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 690e3c2700c6c..f4903023e8059 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -2091,7 +2091,7 @@ def _maybe_require_matching_dtypes(
) -> None:
# TODO: why do we do this for AsOfMerge but not the others?
- def _check_dtype_match(left: ArrayLike, right: ArrayLike, i: int):
+ def _check_dtype_match(left: ArrayLike, right: ArrayLike, i: int) -> None:
if left.dtype != right.dtype:
if isinstance(left.dtype, CategoricalDtype) and isinstance(
right.dtype, CategoricalDtype
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 7a49682d7c57c..3493f1c78da91 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -188,7 +188,7 @@ def _make_sorted_values(self, values: np.ndarray) -> np.ndarray:
return sorted_values
return values
- def _make_selectors(self):
+ def _make_selectors(self) -> None:
new_levels = self.new_index_levels
# make the mask
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index e78bd258c11ff..fa5b84fefb883 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -1143,7 +1143,7 @@ class Window(BaseWindow):
"method",
]
- def _validate(self):
+ def _validate(self) -> None:
super()._validate()
if not isinstance(self.win_type, str):
@@ -1861,7 +1861,7 @@ class Rolling(RollingAndExpandingMixin):
"method",
]
- def _validate(self):
+ def _validate(self) -> None:
super()._validate()
# we allow rolling on a datetimelike index
@@ -2906,7 +2906,7 @@ def _get_window_indexer(self) -> GroupbyIndexer:
)
return window_indexer
- def _validate_datetimelike_monotonic(self):
+ def _validate_datetimelike_monotonic(self) -> None:
"""
Validate that each group in self._on is monotonic
"""
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 416b263ba8497..55541e5262719 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -2288,12 +2288,12 @@ def _parse_latex_css_conversion(styles: CSSList) -> CSSList:
Ignore conversion if tagged with `--latex` option, skipped if no conversion found.
"""
- def font_weight(value, arg):
+ def font_weight(value, arg) -> tuple[str, str] | None:
if value in ("bold", "bolder"):
return "bfseries", f"{arg}"
return None
- def font_style(value, arg):
+ def font_style(value, arg) -> tuple[str, str] | None:
if value == "italic":
return "itshape", f"{arg}"
if value == "oblique":
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 1139519d2bcd3..c30238e412450 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3207,7 +3207,7 @@ class SeriesFixed(GenericFixed):
name: Hashable
@property
- def shape(self):
+ def shape(self) -> tuple[int] | None:
try:
return (len(self.group.values),)
except (TypeError, AttributeError):
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56628 | 2023-12-26T21:39:19Z | 2023-12-27T18:54:54Z | 2023-12-27T18:54:54Z | 2024-01-17T02:50:00Z |
added negative value support in pct_changes of generic.py | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index de25a02c6b37c..fddb4b207c8d3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -11975,6 +11975,7 @@ def pct_change(
fill_method: FillnaOptions | None | lib.NoDefault = lib.no_default,
limit: int | None | lib.NoDefault = lib.no_default,
freq=None,
+ use_absolute_value=False,
**kwargs,
) -> Self:
"""
@@ -12145,7 +12146,10 @@ def pct_change(
shifted = data.shift(periods=periods, freq=freq, axis=axis, **kwargs)
# Unsupported left operand type for / ("Self")
- rs = data / shifted - 1 # type: ignore[operator]
+ if use_absolute_value:
+ rs = (data - shifted) / abs(shifted) # type: ignore[operator]
+ else:
+ rs = data / shifted - 1 # type: ignore[operator]
if freq is not None:
# Shift method is implemented differently when freq is not None
# We want to restore the original index
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 089e15afd465b..908248a037a12 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -5331,6 +5331,7 @@ def pct_change(
fill_method: FillnaOptions | None | lib.NoDefault = lib.no_default,
limit: int | None | lib.NoDefault = lib.no_default,
freq=None,
+ use_absolute_value=False,
axis: Axis | lib.NoDefault = lib.no_default,
):
"""
@@ -5422,6 +5423,7 @@ def pct_change(
limit=limit,
freq=freq,
axis=axis,
+ use_absolute_value=use_absolute_value,
)
return self._python_apply_general(f, self._selected_obj, is_transform=True)
@@ -5436,6 +5438,8 @@ def pct_change(
shifted = fill_grp.shift(periods=periods, freq=freq)
if self.axis == 1:
shifted = shifted.T
+ if use_absolute_value:
+ return (filled - shifted) / abs(shifted)
return (filled / shifted) - 1
@final
diff --git a/pandas/tests/series/methods/test_pct_change.py b/pandas/tests/series/methods/test_pct_change.py
index 9727ef3d5c27c..adec8b6496ee3 100644
--- a/pandas/tests/series/methods/test_pct_change.py
+++ b/pandas/tests/series/methods/test_pct_change.py
@@ -1,6 +1,7 @@
import numpy as np
import pytest
+import pandas as pd
from pandas import (
Series,
date_range,
@@ -75,22 +76,30 @@ def test_pct_change_periods_freq(
# GH#7292
with tm.assert_produces_warning(FutureWarning, match=msg):
rs_freq = datetime_series.pct_change(
- freq=freq, fill_method=fill_method, limit=limit
+ freq=freq,
+ fill_method=fill_method,
+ limit=limit,
)
with tm.assert_produces_warning(FutureWarning, match=msg):
rs_periods = datetime_series.pct_change(
- periods, fill_method=fill_method, limit=limit
+ periods,
+ fill_method=fill_method,
+ limit=limit,
)
tm.assert_series_equal(rs_freq, rs_periods)
empty_ts = Series(index=datetime_series.index, dtype=object)
with tm.assert_produces_warning(FutureWarning, match=msg):
rs_freq = empty_ts.pct_change(
- freq=freq, fill_method=fill_method, limit=limit
+ freq=freq,
+ fill_method=fill_method,
+ limit=limit,
)
with tm.assert_produces_warning(FutureWarning, match=msg):
rs_periods = empty_ts.pct_change(
- periods, fill_method=fill_method, limit=limit
+ periods,
+ fill_method=fill_method,
+ limit=limit,
)
tm.assert_series_equal(rs_freq, rs_periods)
@@ -118,3 +127,19 @@ def test_pct_change_no_warning_na_beginning():
result = ser.pct_change()
expected = Series([np.nan, np.nan, np.nan, 1, 0.5])
tm.assert_series_equal(result, expected)
+
+
+def test_pct_changes_with_negative_values():
+ test = pd.DataFrame()
+ test_list = [1, -2, 3, 4, -5, 6, 7, -8, 9, 10]
+ test["data"] = test_list
+ test["pct_changes"] = test["data"].pct_change(use_absolute_value=True)
+
+ expected_result = [
+ None if i == 0 else (test_list[i] - test_list[i - 1]) / abs(test_list[i - 1])
+ for i in range(len(test_list))
+ ]
+
+ expected_result = Series(expected_result, dtype=float)
+ # assertion to check if the result matches the expected result
+ assert test["pct_changes"].equals(expected_result)
| closes #56618
| https://api.github.com/repos/pandas-dev/pandas/pulls/56627 | 2023-12-26T20:05:33Z | 2024-01-08T21:26:22Z | null | 2024-01-08T21:26:23Z |
TST: Remove arraymanager markers | diff --git a/pandas/tests/copy_view/test_astype.py b/pandas/tests/copy_view/test_astype.py
index d462ce3d3187d..3c1a157dd2c6a 100644
--- a/pandas/tests/copy_view/test_astype.py
+++ b/pandas/tests/copy_view/test_astype.py
@@ -4,7 +4,6 @@
import pytest
from pandas.compat.pyarrow import pa_version_under12p0
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -88,7 +87,6 @@ def test_astype_different_target_dtype(using_copy_on_write, dtype):
tm.assert_frame_equal(df2, df_orig.astype(dtype))
-@td.skip_array_manager_invalid_test
def test_astype_numpy_to_ea():
ser = Series([1, 2, 3])
with pd.option_context("mode.copy_on_write", True):
diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py
index a727331307d7e..615b024bd06bf 100644
--- a/pandas/tests/copy_view/test_internals.py
+++ b/pandas/tests/copy_view/test_internals.py
@@ -1,15 +1,12 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
-@td.skip_array_manager_invalid_test
def test_consolidate(using_copy_on_write):
# create unconsolidated DataFrame
df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
@@ -46,7 +43,6 @@ def test_consolidate(using_copy_on_write):
@pytest.mark.single_cpu
-@td.skip_array_manager_invalid_test
def test_switch_options():
# ensure we can switch the value of the option within one session
# (assuming data is constructed after switching)
@@ -75,7 +71,6 @@ def test_switch_options():
assert df.iloc[0, 0] == 0
-@td.skip_array_manager_invalid_test
@pytest.mark.parametrize("dtype", [np.intp, np.int8])
@pytest.mark.parametrize(
"locs, arr",
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 7837adec0c9e0..e3a467e8bf65b 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -15,7 +15,6 @@
PerformanceWarning,
SettingWithCopyError,
)
-import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_integer
@@ -574,7 +573,6 @@ def test_getitem_setitem_integer_slice_keyerrors(self):
with pytest.raises(KeyError, match=r"^3$"):
df2.loc[3:11] = 0
- @td.skip_array_manager_invalid_test # already covered in test_iloc_col_slice_view
def test_fancy_getitem_slice_mixed(
self, float_frame, float_string_frame, using_copy_on_write, warn_copy_on_write
):
@@ -640,7 +638,6 @@ def test_getitem_fancy_scalar(self, float_frame):
for idx in f.index[::5]:
assert ix[idx, col] == ts[idx]
- @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
def test_setitem_fancy_scalar(self, float_frame):
f = float_frame
expected = float_frame.copy()
@@ -680,7 +677,6 @@ def test_getitem_fancy_boolean(self, float_frame):
expected = f.reindex(index=f.index[boolvec], columns=["C", "D"])
tm.assert_frame_equal(result, expected)
- @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
def test_setitem_fancy_boolean(self, float_frame):
# from 2d, set with booleans
frame = float_frame.copy()
@@ -1404,7 +1400,6 @@ def test_loc_setitem_rhs_frame(self, idxr, val, warn):
expected = DataFrame({"a": [np.nan, val]})
tm.assert_frame_equal(df, expected)
- @td.skip_array_manager_invalid_test
def test_iloc_setitem_enlarge_no_warning(self, warn_copy_on_write):
# GH#47381
df = DataFrame(columns=["a", "b"])
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index f031cb2218e31..0e0f8cf61d3d7 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas.core.dtypes.base import _registry as ea_registry
from pandas.core.dtypes.common import is_object_dtype
from pandas.core.dtypes.dtypes import (
@@ -704,8 +702,6 @@ def test_setitem_ea_dtype_rhs_series(self):
expected = DataFrame({"a": [1, 2]}, dtype="Int64")
tm.assert_frame_equal(df, expected)
- # TODO(ArrayManager) set column with 2d column array, see #44788
- @td.skip_array_manager_not_yet_implemented
def test_setitem_npmatrix_2d(self):
# GH#42376
# for use-case df["x"] = sparse.random((10, 10)).mean(axis=1)
@@ -1063,7 +1059,6 @@ def inc(x):
class TestDataFrameSetItemBooleanMask:
- @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
@pytest.mark.parametrize(
"mask_type",
[lambda df: df > np.abs(df) / 2, lambda df: (df > np.abs(df) / 2).values],
@@ -1307,7 +1302,6 @@ def test_setitem_not_operating_inplace(self, value, set_value, indexer):
df[indexer] = set_value
tm.assert_frame_equal(view, expected)
- @td.skip_array_manager_invalid_test
def test_setitem_column_update_inplace(
self, using_copy_on_write, warn_copy_on_write
):
diff --git a/pandas/tests/frame/methods/test_copy.py b/pandas/tests/frame/methods/test_copy.py
index e7901ed363106..6208d0256a655 100644
--- a/pandas/tests/frame/methods/test_copy.py
+++ b/pandas/tests/frame/methods/test_copy.py
@@ -46,7 +46,6 @@ def test_copy(self, float_frame, float_string_frame):
copy = float_string_frame.copy()
assert copy._mgr is not float_string_frame._mgr
- @td.skip_array_manager_invalid_test
def test_copy_consolidates(self):
# GH#42477
df = DataFrame(
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index 6757669351c5c..4131138a7c588 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -3,8 +3,6 @@
from pandas._config import using_pyarrow_string_dtype
-import pandas.util._test_decorators as td
-
from pandas import (
Categorical,
DataFrame,
@@ -49,7 +47,6 @@ def test_fillna_dict_inplace_nonunique_columns(
if not using_copy_on_write:
assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2])
- @td.skip_array_manager_not_yet_implemented
def test_fillna_on_column_view(self, using_copy_on_write):
# GH#46149 avoid unnecessary copies
arr = np.full((40, 50), np.nan)
@@ -752,7 +749,6 @@ def test_fillna_inplace_with_columns_limit_and_value(self):
df.fillna(axis=1, value=100, limit=1, inplace=True)
tm.assert_frame_equal(df, expected)
- @td.skip_array_manager_invalid_test
@pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}])
def test_inplace_dict_update_view(
self, val, using_copy_on_write, warn_copy_on_write
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index a93931a970687..e377fdd635bfe 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -470,7 +470,7 @@ def test_interp_string_axis(self, axis_name, axis_number):
@pytest.mark.parametrize("multiblock", [True, False])
@pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])
- def test_interp_fillna_methods(self, request, axis, multiblock, method):
+ def test_interp_fillna_methods(self, axis, multiblock, method):
# GH 12918
df = DataFrame(
{
diff --git a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
index 1fe28cb8eb856..086986702d24f 100644
--- a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
+++ b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
@@ -1,16 +1,11 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
Categorical,
DataFrame,
)
-# _is_homogeneous_type always returns True for ArrayManager
-pytestmark = td.skip_array_manager_invalid_test
-
@pytest.mark.parametrize(
"data, expected",
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index d862e14ce86cb..d2ec84bc9371f 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -13,7 +13,6 @@
is_platform_windows,
)
from pandas.compat.numpy import np_version_gt2
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -136,7 +135,6 @@ class TestDataFrameSelectReindex:
reason="Passes int32 values to DatetimeArray in make_na_array on "
"windows, 32bit linux builds",
)
- @td.skip_array_manager_not_yet_implemented
def test_reindex_tzaware_fill_value(self):
# GH#52586
df = DataFrame([[1]])
@@ -198,7 +196,6 @@ def test_reindex_copies_ea(self, using_copy_on_write):
else:
assert not np.shares_memory(result2[0].array._data, df[0].array._data)
- @td.skip_array_manager_not_yet_implemented
def test_reindex_date_fill_value(self):
# passing date to dt64 is deprecated; enforced in 2.0 to cast to object
arr = date_range("2016-01-01", periods=6).values.reshape(3, 2)
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index 907ff67eac7a1..c477c9c1852b7 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
CategoricalIndex,
@@ -464,7 +462,6 @@ def test_shift_axis1_multiple_blocks(self):
tm.assert_frame_equal(result, expected)
- @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) axis=1 support
def test_shift_axis1_multiple_blocks_with_int_fill(self):
# GH#42719
rng = np.random.default_rng(2)
diff --git a/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/pandas/tests/frame/methods/test_to_dict_of_blocks.py
index f64cfd5fe6a2d..217010ab2e7ee 100644
--- a/pandas/tests/frame/methods/test_to_dict_of_blocks.py
+++ b/pandas/tests/frame/methods/test_to_dict_of_blocks.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
MultiIndex,
@@ -10,8 +8,6 @@
import pandas._testing as tm
from pandas.core.arrays import NumpyExtensionArray
-pytestmark = td.skip_array_manager_invalid_test
-
class TestToDictOfBlocks:
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
diff --git a/pandas/tests/frame/methods/test_to_numpy.py b/pandas/tests/frame/methods/test_to_numpy.py
index bdb9b2c055061..d92af2775922b 100644
--- a/pandas/tests/frame/methods/test_to_numpy.py
+++ b/pandas/tests/frame/methods/test_to_numpy.py
@@ -1,7 +1,5 @@
import numpy as np
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
Timestamp,
@@ -22,7 +20,6 @@ def test_to_numpy_dtype(self):
result = df.to_numpy(dtype="int64")
tm.assert_numpy_array_equal(result, expected)
- @td.skip_array_manager_invalid_test
def test_to_numpy_copy(self, using_copy_on_write):
arr = np.random.default_rng(2).standard_normal((4, 3))
df = DataFrame(arr)
diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py
index d0caa071fae1c..45bd8ff0268a8 100644
--- a/pandas/tests/frame/methods/test_transpose.py
+++ b/pandas/tests/frame/methods/test_transpose.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
DatetimeIndex,
@@ -126,7 +124,6 @@ def test_transpose_mixed(self):
for col, s in mixed_T.items():
assert s.dtype == np.object_
- @td.skip_array_manager_invalid_test
def test_transpose_get_view(self, float_frame, using_copy_on_write):
dft = float_frame.T
dft.iloc[:, 5:10] = 5
@@ -136,7 +133,6 @@ def test_transpose_get_view(self, float_frame, using_copy_on_write):
else:
assert (float_frame.values[5:10] == 5).all()
- @td.skip_array_manager_invalid_test
def test_transpose_get_view_dt64tzget_view(self, using_copy_on_write):
dti = date_range("2016-01-01", periods=6, tz="US/Pacific")
arr = dti._data.reshape(3, 2)
diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py
index 7c7a0d23ff75f..fd4c9d64d656e 100644
--- a/pandas/tests/frame/methods/test_update.py
+++ b/pandas/tests/frame/methods/test_update.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
DataFrame,
@@ -175,7 +173,6 @@ def test_update_with_different_dtype(self, using_copy_on_write):
)
tm.assert_frame_equal(df, expected)
- @td.skip_array_manager_invalid_test
def test_update_modify_view(
self, using_copy_on_write, warn_copy_on_write, using_infer_string
):
diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py
index bbca4ee1b88b1..f1230e55f9054 100644
--- a/pandas/tests/frame/methods/test_values.py
+++ b/pandas/tests/frame/methods/test_values.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
NaT,
@@ -15,7 +13,6 @@
class TestDataFrameValues:
- @td.skip_array_manager_invalid_test
def test_values(self, float_frame, using_copy_on_write):
if using_copy_on_write:
with pytest.raises(ValueError, match="read-only"):
@@ -231,7 +228,6 @@ def test_values_lcd(self, mixed_float_frame, mixed_int_frame):
class TestPrivateValues:
- @td.skip_array_manager_invalid_test
def test_private_values_dt64tz(self, using_copy_on_write):
dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1)
@@ -249,7 +245,6 @@ def test_private_values_dt64tz(self, using_copy_on_write):
df2 = df - df
tm.assert_equal(df2._values, tda)
- @td.skip_array_manager_invalid_test
def test_private_values_dt64tz_multicol(self, using_copy_on_write):
dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2)
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index ecaf826c46d9b..be6ed91973e80 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -896,7 +896,6 @@ def test_df_arith_2d_array_rowlike_broadcasts(
):
# GH#23000
opname = all_arithmetic_operators
-
arr = np.arange(6).reshape(3, 2)
df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
@@ -919,7 +918,6 @@ def test_df_arith_2d_array_collike_broadcasts(
):
# GH#23000
opname = all_arithmetic_operators
-
arr = np.arange(6).reshape(3, 2)
df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index 712494ef15f97..22fff2116510a 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -8,7 +8,6 @@
import pytest
from pandas.errors import PerformanceWarning
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -26,11 +25,6 @@
# structure
-# TODO(ArrayManager) check which of those tests need to be rewritten to test the
-# equivalent for ArrayManager
-pytestmark = td.skip_array_manager_invalid_test
-
-
class TestDataFrameBlockInternals:
def test_setitem_invalidates_datetime_index_freq(self):
# GH#24096 altering a datetime64tz column inplace invalidates the
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 8ff69472ea113..aefb0377d1bf4 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -25,7 +25,6 @@
from pandas._libs import lib
from pandas.errors import IntCastingNaNError
-import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_integer_dtype
from pandas.core.dtypes.dtypes import (
@@ -324,7 +323,6 @@ def test_constructor_dtype_nocast_view_2d_array(
df2 = DataFrame(df.values, dtype=df[0].dtype)
assert df2._mgr.arrays[0].flags.c_contiguous
- @td.skip_array_manager_invalid_test
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="conversion copies")
def test_1d_object_array_does_not_copy(self):
# https://github.com/pandas-dev/pandas/issues/39272
@@ -332,7 +330,6 @@ def test_1d_object_array_does_not_copy(self):
df = DataFrame(arr, copy=False)
assert np.shares_memory(df.values, arr)
- @td.skip_array_manager_invalid_test
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="conversion copies")
def test_2d_object_array_does_not_copy(self):
# https://github.com/pandas-dev/pandas/issues/39272
@@ -2489,7 +2486,6 @@ def test_constructor_list_str_na(self, string_dtype):
@pytest.mark.parametrize("copy", [False, True])
def test_dict_nocopy(
self,
- request,
copy,
any_numeric_ea_dtype,
any_numpy_dtype,
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 512b5d6ace469..dd88e7401a03f 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1701,7 +1701,6 @@ def test_reductions_skipna_none_raises(
with pytest.raises(ValueError, match=msg):
getattr(obj, all_reductions)(skipna=None)
- @td.skip_array_manager_invalid_test
def test_reduction_timestamp_smallest_unit(self):
# GH#52524
df = DataFrame(
@@ -1720,7 +1719,6 @@ def test_reduction_timestamp_smallest_unit(self):
)
tm.assert_series_equal(result, expected)
- @td.skip_array_manager_not_yet_implemented
def test_reduction_timedelta_smallest_unit(self):
# GH#52524
df = DataFrame(
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index 49b2e621b7adc..ac5374597585a 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -2,7 +2,6 @@
import pytest
from pandas._libs import lib
-import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
@@ -22,7 +21,7 @@ def cumsum_max(x):
"func",
[
cumsum_max,
- pytest.param(assert_block_lengths, marks=td.skip_array_manager_invalid_test),
+ assert_block_lengths,
],
)
def test_mgr_locs_updated(func):
diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
index 0dd1a56890fee..014ba6fc12b72 100644
--- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
@@ -3,7 +3,6 @@
from pandas._libs import index as libindex
from pandas.errors import SettingWithCopyError
-import pandas.util._test_decorators as td
from pandas import (
DataFrame,
@@ -43,7 +42,6 @@ def test_detect_chained_assignment(using_copy_on_write, warn_copy_on_write):
zed["eyes"]["right"].fillna(value=555, inplace=True)
-@td.skip_array_manager_invalid_test # with ArrayManager df.loc[0] is not a view
def test_cache_updating(using_copy_on_write, warn_copy_on_write):
# 5216
# make sure that we don't try to set a dead cache
diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py
index fdf88b2a97e46..5aff1f1309004 100644
--- a/pandas/tests/indexing/multiindex/test_partial.py
+++ b/pandas/tests/indexing/multiindex/test_partial.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
DatetimeIndex,
@@ -118,9 +116,6 @@ def test_getitem_partial_column_select(self):
with pytest.raises(KeyError, match=r"\('a', 'foo'\)"):
df.loc[("a", "foo"), :]
- # TODO(ArrayManager) rewrite test to not use .values
- # exp.loc[2000, 4].values[:] select multiple columns -> .values is not a view
- @td.skip_array_manager_invalid_test
def test_partial_set(
self,
multiindex_year_month_day_dataframe_random_data,
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index 53ad4d6b41687..22a0a49762097 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -2,7 +2,6 @@
import pytest
from pandas.errors import SettingWithCopyError
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -126,9 +125,6 @@ def test_setitem_multiindex3(self):
expected=copy,
)
- # TODO(ArrayManager) df.loc["bar"] *= 2 doesn't raise an error but results in
- # all NaNs -> doesn't work in the "split" path (also for BlockManager actually)
- @td.skip_array_manager_not_yet_implemented
def test_multiindex_setitem(self):
# GH 3738
# setting with a multi-index right hand side
@@ -520,8 +516,6 @@ def test_setitem_enlargement_keep_index_names(self):
tm.assert_frame_equal(df, expected)
-@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
-# is not a view
def test_frame_setitem_view_direct(
multiindex_dataframe_random_data, using_copy_on_write
):
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index ca796463f4a1e..5eeaa50e2c3b6 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -7,7 +7,6 @@
SettingWithCopyError,
SettingWithCopyWarning,
)
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -539,8 +538,6 @@ def test_detect_chained_assignment_warning_stacklevel(
chained[2] = rhs
tm.assert_frame_equal(df, df_original)
- # TODO(ArrayManager) fast_xs with array-like scalars is not yet working
- @td.skip_array_manager_not_yet_implemented
def test_chained_getitem_with_lists(self):
# GH6394
# Regression in chained getitem indexing with embedded list-like from
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index a1d8577d534f5..13d786f98c42b 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -7,7 +7,6 @@
import pytest
from pandas.errors import IndexingError
-import pandas.util._test_decorators as td
from pandas import (
NA,
@@ -1193,7 +1192,6 @@ def test_iloc_setitem_2d_ndarray_into_ea_block(self):
expected = DataFrame({"status": ["a", "a", "c"]}, dtype=df["status"].dtype)
tm.assert_frame_equal(df, expected)
- @td.skip_array_manager_not_yet_implemented
def test_iloc_getitem_int_single_ea_block_view(self):
# GH#45241
# TODO: make an extension interface test for this?
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index da10555e60301..1aa988cca0400 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -17,7 +17,6 @@
from pandas._libs import index as libindex
from pandas.compat.numpy import np_version_gt2
from pandas.errors import IndexingError
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -2640,7 +2639,6 @@ def test_loc_setitem_mask_td64_series_value(self):
assert expected == result
tm.assert_frame_equal(df, df_copy)
- @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
def test_loc_setitem_boolean_and_column(self, float_frame):
expected = float_frame.copy()
mask = float_frame["A"] > 0
@@ -3315,7 +3313,6 @@ def test_loc_assign_dict_to_row(self, dtype):
tm.assert_frame_equal(df, expected)
- @td.skip_array_manager_invalid_test
def test_loc_setitem_dict_timedelta_multiple_set(self):
# GH 16309
result = DataFrame(columns=["time", "value"])
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 2265522bc7ecb..66dd893df51de 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -10,7 +10,6 @@
from pandas._libs.internals import BlockPlacement
from pandas.compat import IS64
-import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_scalar
@@ -44,10 +43,6 @@
new_block,
)
-# this file contains BlockManager specific tests
-# TODO(ArrayManager) factor out interleave_dtype tests
-pytestmark = td.skip_array_manager_invalid_test
-
@pytest.fixture(params=[new_block, make_block])
def block_maker(request):
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index 00a81a4f1f385..706610316ef43 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -6,7 +6,6 @@
import pytest
from pandas._libs.tslibs import Timestamp
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -733,10 +732,6 @@ def test_append_misc_empty_frame(setup_path):
tm.assert_frame_equal(store.select("df2"), df)
-# TODO(ArrayManager) currently we rely on falling back to BlockManager, but
-# the conversion from AM->BM converts the invalid object dtype column into
-# a datetime64 column no longer raising an error
-@td.skip_array_manager_not_yet_implemented
def test_append_raise(setup_path):
with ensure_clean_store(setup_path) as store:
# test append with invalid input to get good error messages
diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py
index a1dec8a2d05b4..f6fb032b9d51a 100644
--- a/pandas/tests/io/test_fsspec.py
+++ b/pandas/tests/io/test_fsspec.py
@@ -194,7 +194,6 @@ def test_arrowparquet_options(fsspectest):
assert fsspectest.test[0] == "parquet_read"
-@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet
def test_fastparquet_options(fsspectest):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
pytest.importorskip("fastparquet")
@@ -253,7 +252,6 @@ def test_s3_protocols(s3_public_bucket_with_data, tips_file, protocol, s3so):
@pytest.mark.single_cpu
-@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet
def test_s3_parquet(s3_public_bucket, s3so, df1):
pytest.importorskip("fastparquet")
pytest.importorskip("s3fs")
diff --git a/pandas/tests/io/test_http_headers.py b/pandas/tests/io/test_http_headers.py
index 2ca11ad1f74e6..550637a50c1c4 100644
--- a/pandas/tests/io/test_http_headers.py
+++ b/pandas/tests/io/test_http_headers.py
@@ -100,11 +100,9 @@ def stata_responder(df):
pytest.param(
parquetfastparquet_responder,
partial(pd.read_parquet, engine="fastparquet"),
- # TODO(ArrayManager) fastparquet
marks=[
td.skip_if_no("fastparquet"),
td.skip_if_no("fsspec"),
- td.skip_array_manager_not_yet_implemented,
],
),
(pickle_respnder, pd.read_pickle),
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py
index 4f3993a038197..4e1f09b929224 100644
--- a/pandas/tests/io/test_pickle.py
+++ b/pandas/tests/io/test_pickle.py
@@ -37,7 +37,6 @@
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.compressors import flatten_buffer
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -600,7 +599,6 @@ def test_pickle_strings(string_series):
tm.assert_series_equal(unp_series, string_series)
-@td.skip_array_manager_invalid_test
def test_pickle_preserves_block_ndim():
# GH#37631
ser = Series(list("abc")).astype("category").iloc[[0]]
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py
index 2cc91992f1fd7..5ec95cbf24b39 100644
--- a/pandas/tests/reshape/concat/test_concat.py
+++ b/pandas/tests/reshape/concat/test_concat.py
@@ -10,7 +10,6 @@
import pytest
from pandas.errors import InvalidIndexError
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -773,7 +772,6 @@ def test_concat_retain_attrs(data):
assert df.attrs[1] == 1
-@td.skip_array_manager_invalid_test
@pytest.mark.parametrize("df_dtype", ["float64", "int64", "datetime64[ns]"])
@pytest.mark.parametrize("empty_dtype", [None, "float64", "object"])
def test_concat_ignore_empty_object_float(empty_dtype, df_dtype):
@@ -799,7 +797,6 @@ def test_concat_ignore_empty_object_float(empty_dtype, df_dtype):
tm.assert_frame_equal(result, expected)
-@td.skip_array_manager_invalid_test
@pytest.mark.parametrize("df_dtype", ["float64", "int64", "datetime64[ns]"])
@pytest.mark.parametrize("empty_dtype", [None, "float64", "object"])
def test_concat_ignore_all_na_object_float(empty_dtype, df_dtype):
@@ -827,7 +824,6 @@ def test_concat_ignore_all_na_object_float(empty_dtype, df_dtype):
tm.assert_frame_equal(result, expected)
-@td.skip_array_manager_invalid_test
def test_concat_ignore_empty_from_reindex():
# https://github.com/pandas-dev/pandas/pull/43507#issuecomment-920375856
df1 = DataFrame({"a": [1], "b": [pd.Timestamp("2012-01-01")]})
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index 1a4a390da1323..1959e71f60775 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -3,8 +3,6 @@
from pandas._config import using_pyarrow_string_dtype
-import pandas.util._test_decorators as td
-
from pandas import (
NA,
Categorical,
@@ -315,7 +313,6 @@ def test_reindex_fill_value():
tm.assert_series_equal(result, expected)
-@td.skip_array_manager_not_yet_implemented
@pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"])
@pytest.mark.parametrize("fill_value", ["string", 0, Timedelta(0)])
def test_reindex_fill_value_datetimelike_upcast(dtype, fill_value):
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 866bfb995a6d5..b802e92e4fcca 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -16,7 +16,6 @@
)
from pandas.compat.numpy import np_version_gt2
from pandas.errors import IntCastingNaNError
-import pandas.util._test_decorators as td
from pandas.core.dtypes.dtypes import CategoricalDtype
@@ -702,7 +701,6 @@ def test_constructor_copy(self):
assert x[0] == 2.0
assert y[0] == 1.0
- @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite test
@pytest.mark.parametrize(
"index",
[
@@ -2194,7 +2192,6 @@ def test_constructor_no_pandas_array(self):
assert isinstance(result._mgr.blocks[0], NumpyBlock)
assert result._mgr.blocks[0].is_numeric
- @td.skip_array_manager_invalid_test
def test_from_array(self):
result = Series(pd.array(["1h", "2h"], dtype="timedelta64[ns]"))
assert result._mgr.blocks[0].is_extension is False
@@ -2202,7 +2199,6 @@ def test_from_array(self):
result = Series(pd.array(["2015"], dtype="datetime64[ns]"))
assert result._mgr.blocks[0].is_extension is False
- @td.skip_array_manager_invalid_test
def test_from_list_dtype(self):
result = Series(["1h", "2h"], dtype="timedelta64[ns]")
assert result._mgr.blocks[0].is_extension is False
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 2c1912bce856d..37908c9ac255b 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -38,7 +38,6 @@ def test_foo():
if TYPE_CHECKING:
from pandas._typing import F
-from pandas._config.config import _get_option
from pandas.compat import (
IS64,
@@ -147,21 +146,6 @@ def documented_fixture(fixture):
return documented_fixture
-def mark_array_manager_not_yet_implemented(request) -> None:
- mark = pytest.mark.xfail(reason="Not yet implemented for ArrayManager")
- request.applymarker(mark)
-
-
-skip_array_manager_not_yet_implemented = pytest.mark.xfail(
- _get_option("mode.data_manager", silent=True) == "array",
- reason="Not yet implemented for ArrayManager",
-)
-
-skip_array_manager_invalid_test = pytest.mark.skipif(
- _get_option("mode.data_manager", silent=True) == "array",
- reason="Test that relies on BlockManager internals or specific behaviour",
-)
-
skip_copy_on_write_not_yet_implemented = pytest.mark.xfail(
get_option("mode.copy_on_write") is True,
reason="Not yet implemented/adapted for Copy-on-Write mode",
| No longer really necessary since we don't test this in the CI anymore | https://api.github.com/repos/pandas-dev/pandas/pulls/56626 | 2023-12-26T19:46:45Z | 2023-12-27T15:30:31Z | 2023-12-27T15:30:31Z | 2023-12-27T18:08:27Z |
TST/CLN: Remove more seldom used fixtures | diff --git a/pandas/conftest.py b/pandas/conftest.py
index c325a268fe418..4a3fb5c2916c6 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1838,16 +1838,6 @@ def ip():
return InteractiveShell(config=c)
-@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
-def spmatrix(request):
- """
- Yields scipy sparse matrix classes.
- """
- sparse = pytest.importorskip("scipy.sparse")
-
- return getattr(sparse, request.param + "_matrix")
-
-
@pytest.fixture(
params=[
getattr(pd.offsets, o)
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index ebcd7cbd963d7..121bfb78fe5c8 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -37,14 +37,6 @@ def switch_numexpr_min_elements(request, monkeypatch):
yield request.param
-@pytest.fixture(params=[Index, Series, tm.to_array])
-def box_pandas_1d_array(request):
- """
- Fixture to test behavior for Index, Series and tm.to_array classes
- """
- return request.param
-
-
@pytest.fixture(
params=[
# TODO: add more dtypes here
@@ -62,17 +54,6 @@ def numeric_idx(request):
return request.param
-@pytest.fixture(
- params=[Index, Series, tm.to_array, np.array, list], ids=lambda x: x.__name__
-)
-def box_1d_array(request):
- """
- Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list
- classes
- """
- return request.param
-
-
def adjust_negative_zero(zero, expected):
"""
Helper to adjust the expected result if we are dividing by -0.0
@@ -1499,6 +1480,8 @@ def test_dataframe_div_silenced():
"data, expected_data",
[([0, 1, 2], [0, 2, 4])],
)
+@pytest.mark.parametrize("box_pandas_1d_array", [Index, Series, tm.to_array])
+@pytest.mark.parametrize("box_1d_array", [Index, Series, tm.to_array, np.array, list])
def test_integer_array_add_list_like(
box_pandas_1d_array, box_1d_array, data, expected_data
):
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 3ec6d70494902..e2ef83c243957 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1977,9 +1977,12 @@ def test_nan_to_nat_conversions():
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
+@pytest.mark.parametrize("spmatrix", ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
def test_is_scipy_sparse(spmatrix):
- pytest.importorskip("scipy")
- assert is_scipy_sparse(spmatrix([[0, 1]]))
+ sparse = pytest.importorskip("scipy.sparse")
+
+ klass = getattr(sparse, spmatrix + "_matrix")
+ assert is_scipy_sparse(klass([[0, 1]]))
assert not is_scipy_sparse(np.array([1]))
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index e3a467e8bf65b..1b83c048411a8 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -1662,25 +1662,6 @@ def orig(self):
orig = DataFrame({"cats": cats, "values": values}, index=idx)
return orig
- @pytest.fixture
- def exp_single_row(self):
- # The expected values if we change a single row
- cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
- idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
- values1 = [1, 1, 2, 1, 1, 1, 1]
- exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
- return exp_single_row
-
- @pytest.fixture
- def exp_multi_row(self):
- # assign multiple rows (mixed values) (-> array) -> exp_multi_row
- # changed multiple rows
- cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
- idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
- values2 = [1, 1, 2, 2, 1, 1, 1]
- exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
- return exp_multi_row
-
@pytest.fixture
def exp_parts_cats_col(self):
# changed part of the cats column
@@ -1702,7 +1683,7 @@ def exp_single_cats_value(self):
return exp_single_cats_value
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer):
+ def test_loc_iloc_setitem_list_of_lists(self, orig, indexer):
# - assign multiple rows (mixed values) -> exp_multi_row
df = orig.copy()
@@ -1711,6 +1692,11 @@ def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer):
key = slice("j", "k")
indexer(df)[key, :] = [["b", 2], ["b", 2]]
+
+ cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
+ idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
+ values2 = [1, 1, 2, 2, 1, 1, 1]
+ exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
tm.assert_frame_equal(df, exp_multi_row)
df = orig.copy()
@@ -1752,9 +1738,7 @@ def test_loc_iloc_setitem_mask_single_value_in_categories(
tm.assert_frame_equal(df, exp_single_cats_value)
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_loc_iloc_setitem_full_row_non_categorical_rhs(
- self, orig, exp_single_row, indexer
- ):
+ def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer):
# - assign a complete row (mixed values) -> exp_single_row
df = orig.copy()
@@ -1764,6 +1748,10 @@ def test_loc_iloc_setitem_full_row_non_categorical_rhs(
# not categorical dtype, but "b" _is_ among the categories for df["cat"]
indexer(df)[key, :] = ["b", 2]
+ cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
+ idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
+ values1 = [1, 1, 2, 1, 1, 1, 1]
+ exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
tm.assert_frame_equal(df, exp_single_row)
# "c" is not among the categories for df["cat"]
diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index 02f0b9e20871d..82802dd6e99eb 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -17,25 +17,6 @@
from pandas.core.reshape.concat import concat
-@pytest.fixture
-def frame_with_period_index():
- return DataFrame(
- data=np.arange(20).reshape(4, 5),
- columns=list("abcde"),
- index=period_range(start="2000", freq="Y", periods=4),
- )
-
-
-@pytest.fixture
-def left():
- return DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
-
-
-@pytest.fixture
-def right():
- return DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
-
-
@pytest.fixture
def left_no_dup():
return DataFrame(
@@ -112,7 +93,9 @@ def right_w_dups(right_no_dup):
),
],
)
-def test_join(left, right, how, sort, expected):
+def test_join(how, sort, expected):
+ left = DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
+ right = DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
result = left.join(right, how=how, sort=sort, validate="1:1")
tm.assert_frame_equal(result, expected)
@@ -347,7 +330,12 @@ def test_join_overlap(float_frame):
tm.assert_frame_equal(joined, expected.loc[:, joined.columns])
-def test_join_period_index(frame_with_period_index):
+def test_join_period_index():
+ frame_with_period_index = DataFrame(
+ data=np.arange(20).reshape(4, 5),
+ columns=list("abcde"),
+ index=period_range(start="2000", freq="Y", periods=4),
+ )
other = frame_with_period_index.rename(columns=lambda key: f"{key}{key}")
joined_values = np.concatenate([frame_with_period_index.values] * 2, axis=1)
diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py
index 3ba893501914a..8a7b985c98069 100644
--- a/pandas/tests/frame/methods/test_nlargest.py
+++ b/pandas/tests/frame/methods/test_nlargest.py
@@ -12,25 +12,6 @@
from pandas.util.version import Version
-@pytest.fixture
-def df_duplicates():
- return pd.DataFrame(
- {"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
- index=[0, 0, 1, 1, 1],
- )
-
-
-@pytest.fixture
-def df_strings():
- return pd.DataFrame(
- {
- "a": np.random.default_rng(2).permutation(10),
- "b": list(ascii_lowercase[:10]),
- "c": np.random.default_rng(2).permutation(10).astype("float64"),
- }
- )
-
-
@pytest.fixture
def df_main_dtypes():
return pd.DataFrame(
@@ -81,9 +62,15 @@ class TestNLargestNSmallest:
],
)
@pytest.mark.parametrize("n", range(1, 11))
- def test_nlargest_n(self, df_strings, nselect_method, n, order):
+ def test_nlargest_n(self, nselect_method, n, order):
# GH#10393
- df = df_strings
+ df = pd.DataFrame(
+ {
+ "a": np.random.default_rng(2).permutation(10),
+ "b": list(ascii_lowercase[:10]),
+ "c": np.random.default_rng(2).permutation(10).astype("float64"),
+ }
+ )
if "b" in order:
error_msg = (
f"Column 'b' has dtype (object|string), "
@@ -156,10 +143,13 @@ def test_nlargest_n_identical_values(self):
[["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]],
)
@pytest.mark.parametrize("n", range(1, 6))
- def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request):
+ def test_nlargest_n_duplicate_index(self, n, order, request):
# GH#13412
- df = df_duplicates
+ df = pd.DataFrame(
+ {"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
+ index=[0, 0, 1, 1, 1],
+ )
result = df.nsmallest(n, order)
expected = df.sort_values(order).head(n)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py
index ef78ae62cb4d6..91f5de8e7d7f3 100644
--- a/pandas/tests/frame/test_subclass.py
+++ b/pandas/tests/frame/test_subclass.py
@@ -15,16 +15,6 @@
)
-@pytest.fixture()
-def gpd_style_subclass_df():
- class SubclassedDataFrame(DataFrame):
- @property
- def _constructor(self):
- return SubclassedDataFrame
-
- return SubclassedDataFrame({"a": [1, 2, 3]})
-
-
class TestDataFrameSubclassing:
def test_frame_subclassing_and_slicing(self):
# Subclass frame and ensure it returns the right class on slicing it
@@ -710,14 +700,21 @@ def test_idxmax_preserves_subclass(self):
result = df.idxmax()
assert isinstance(result, tm.SubclassedSeries)
- def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
+ def test_convert_dtypes_preserves_subclass(self):
# GH 43668
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
result = df.convert_dtypes()
assert isinstance(result, tm.SubclassedDataFrame)
- result = gpd_style_subclass_df.convert_dtypes()
- assert isinstance(result, type(gpd_style_subclass_df))
+ def test_convert_dtypes_preserves_subclass_with_constructor(self):
+ class SubclassedDataFrame(DataFrame):
+ @property
+ def _constructor(self):
+ return SubclassedDataFrame
+
+ df = SubclassedDataFrame({"a": [1, 2, 3]})
+ result = df.convert_dtypes()
+ assert isinstance(result, SubclassedDataFrame)
def test_astype_preserves_subclass(self):
# GH#40810
diff --git a/pandas/tests/frame/test_validate.py b/pandas/tests/frame/test_validate.py
index e99e0a6863848..fdeecba29a617 100644
--- a/pandas/tests/frame/test_validate.py
+++ b/pandas/tests/frame/test_validate.py
@@ -3,11 +3,6 @@
from pandas.core.frame import DataFrame
-@pytest.fixture
-def dataframe():
- return DataFrame({"a": [1, 2], "b": [3, 4]})
-
-
class TestDataFrameValidate:
"""Tests for error handling related to data types of method arguments."""
@@ -24,7 +19,8 @@ class TestDataFrameValidate:
],
)
@pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])
- def test_validate_bool_args(self, dataframe, func, inplace):
+ def test_validate_bool_args(self, func, inplace):
+ dataframe = DataFrame({"a": [1, 2], "b": [3, 4]})
msg = 'For argument "inplace" expected type bool'
kwargs = {"inplace": inplace}
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index 866e9e203ffe3..f25e7d4ab8c79 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -386,18 +386,11 @@ def idfn(x):
return str(x)
-@pytest.fixture(params=_all_methods, ids=lambda x: idfn(x[-1]))
-def ndframe_method(request):
- """
- An NDFrame method returning an NDFrame.
- """
- return request.param
-
-
@pytest.mark.filterwarnings(
"ignore:DataFrame.fillna with 'method' is deprecated:FutureWarning",
"ignore:last is deprecated:FutureWarning",
)
+@pytest.mark.parametrize("ndframe_method", _all_methods, ids=lambda x: idfn(x[-1]))
def test_finalize_called(ndframe_method):
cls, init_args, method = ndframe_method
ndframe = cls(*init_args)
diff --git a/pandas/tests/generic/test_label_or_level_utils.py b/pandas/tests/generic/test_label_or_level_utils.py
index 97be46f716d7d..80c24c647bc11 100644
--- a/pandas/tests/generic/test_label_or_level_utils.py
+++ b/pandas/tests/generic/test_label_or_level_utils.py
@@ -34,15 +34,6 @@ def df_ambig(df):
return df
-@pytest.fixture
-def df_duplabels(df):
- """DataFrame with level 'L1' and labels 'L2', 'L3', and 'L2'"""
- df = df.set_index(["L1"])
- df = pd.concat([df, df["L2"]], axis=1)
-
- return df
-
-
# Test is label/level reference
# =============================
def get_labels_levels(df_levels):
@@ -229,7 +220,9 @@ def test_get_label_or_level_values_df_ambig(df_ambig, axis):
assert_label_values(df_ambig, ["L3"], axis=axis)
-def test_get_label_or_level_values_df_duplabels(df_duplabels, axis):
+def test_get_label_or_level_values_df_duplabels(df, axis):
+ df = df.set_index(["L1"])
+ df_duplabels = pd.concat([df, df["L2"]], axis=1)
axis = df_duplabels._get_axis_number(axis)
# Transpose frame if axis == 1
if axis == 1:
diff --git a/pandas/tests/groupby/methods/test_describe.py b/pandas/tests/groupby/methods/test_describe.py
index f27e99809176c..e73fb15a54181 100644
--- a/pandas/tests/groupby/methods/test_describe.py
+++ b/pandas/tests/groupby/methods/test_describe.py
@@ -226,49 +226,34 @@ def test_describe_duplicate_columns():
tm.assert_frame_equal(result, expected)
-class TestGroupByNonCythonPaths:
+def test_describe_non_cython_paths():
# GH#5610 non-cython calls should not include the grouper
# Tests for code not expected to go through cython paths.
+ df = DataFrame(
+ [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]],
+ columns=["A", "B", "C"],
+ )
+ gb = df.groupby("A")
+ expected_index = Index([1, 3], name="A")
+ expected_col = MultiIndex(
+ levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]],
+ codes=[[0] * 8, list(range(8))],
+ )
+ expected = DataFrame(
+ [
+ [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0],
+ [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
+ ],
+ index=expected_index,
+ columns=expected_col,
+ )
+ result = gb.describe()
+ tm.assert_frame_equal(result, expected)
- @pytest.fixture
- def df(self):
- df = DataFrame(
- [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]],
- columns=["A", "B", "C"],
- )
- return df
-
- @pytest.fixture
- def gb(self, df):
- gb = df.groupby("A")
- return gb
-
- @pytest.fixture
- def gni(self, df):
- gni = df.groupby("A", as_index=False)
- return gni
-
- def test_describe(self, df, gb, gni):
- # describe
- expected_index = Index([1, 3], name="A")
- expected_col = MultiIndex(
- levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]],
- codes=[[0] * 8, list(range(8))],
- )
- expected = DataFrame(
- [
- [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0],
- [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
- ],
- index=expected_index,
- columns=expected_col,
- )
- result = gb.describe()
- tm.assert_frame_equal(result, expected)
-
- expected = expected.reset_index()
- result = gni.describe()
- tm.assert_frame_equal(result, expected)
+ gni = df.groupby("A", as_index=False)
+ expected = expected.reset_index()
+ result = gni.describe()
+ tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("dtype", [int, float, object])
diff --git a/pandas/tests/groupby/methods/test_value_counts.py b/pandas/tests/groupby/methods/test_value_counts.py
index 5c9f7febe32b3..35f2f47f5ff97 100644
--- a/pandas/tests/groupby/methods/test_value_counts.py
+++ b/pandas/tests/groupby/methods/test_value_counts.py
@@ -419,14 +419,6 @@ def test_compound(
tm.assert_frame_equal(result, expected)
-@pytest.fixture
-def animals_df():
- return DataFrame(
- {"key": [1, 1, 1, 1], "num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]},
- index=["falcon", "dog", "cat", "ant"],
- )
-
-
@pytest.mark.parametrize(
"sort, ascending, normalize, name, expected_data, expected_index",
[
@@ -444,10 +436,14 @@ def animals_df():
],
)
def test_data_frame_value_counts(
- animals_df, sort, ascending, normalize, name, expected_data, expected_index
+ sort, ascending, normalize, name, expected_data, expected_index
):
# 3-way compare with :meth:`~DataFrame.value_counts`
# Tests from frame/methods/test_value_counts.py
+ animals_df = DataFrame(
+ {"key": [1, 1, 1, 1], "num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]},
+ index=["falcon", "dog", "cat", "ant"],
+ )
result_frame = animals_df.value_counts(
sort=sort, ascending=ascending, normalize=normalize
)
@@ -467,19 +463,6 @@ def test_data_frame_value_counts(
tm.assert_series_equal(result_frame_groupby, expected)
-@pytest.fixture
-def nulls_df():
- n = np.nan
- return DataFrame(
- {
- "A": [1, 1, n, 4, n, 6, 6, 6, 6],
- "B": [1, 1, 3, n, n, 6, 6, 6, 6],
- "C": [1, 2, 3, 4, 5, 6, n, 8, n],
- "D": [1, 2, 3, 4, 5, 6, 7, n, n],
- }
- )
-
-
@pytest.mark.parametrize(
"group_dropna, count_dropna, expected_rows, expected_values",
[
@@ -495,7 +478,7 @@ def nulls_df():
],
)
def test_dropna_combinations(
- nulls_df, group_dropna, count_dropna, expected_rows, expected_values, request
+ group_dropna, count_dropna, expected_rows, expected_values, request
):
if Version(np.__version__) >= Version("1.25") and not group_dropna:
request.applymarker(
@@ -507,6 +490,14 @@ def test_dropna_combinations(
strict=False,
)
)
+ nulls_df = DataFrame(
+ {
+ "A": [1, 1, np.nan, 4, np.nan, 6, 6, 6, 6],
+ "B": [1, 1, 3, np.nan, np.nan, 6, 6, 6, 6],
+ "C": [1, 2, 3, 4, 5, 6, np.nan, 8, np.nan],
+ "D": [1, 2, 3, 4, 5, 6, 7, np.nan, np.nan],
+ }
+ )
gp = nulls_df.groupby(["A", "B"], dropna=group_dropna)
result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna)
columns = DataFrame()
@@ -517,17 +508,6 @@ def test_dropna_combinations(
tm.assert_series_equal(result, expected)
-@pytest.fixture
-def names_with_nulls_df(nulls_fixture):
- return DataFrame(
- {
- "key": [1, 1, 1, 1],
- "first_name": ["John", "Anne", "John", "Beth"],
- "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"],
- },
- )
-
-
@pytest.mark.parametrize(
"dropna, expected_data, expected_index",
[
@@ -556,11 +536,18 @@ def names_with_nulls_df(nulls_fixture):
)
@pytest.mark.parametrize("normalize, name", [(False, "count"), (True, "proportion")])
def test_data_frame_value_counts_dropna(
- names_with_nulls_df, dropna, normalize, name, expected_data, expected_index
+ nulls_fixture, dropna, normalize, name, expected_data, expected_index
):
# GH 41334
# 3-way compare with :meth:`~DataFrame.value_counts`
# Tests with nulls from frame/methods/test_value_counts.py
+ names_with_nulls_df = DataFrame(
+ {
+ "key": [1, 1, 1, 1],
+ "first_name": ["John", "Anne", "John", "Beth"],
+ "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"],
+ },
+ )
result_frame = names_with_nulls_df.value_counts(dropna=dropna, normalize=normalize)
expected = Series(
data=expected_data,
diff --git a/pandas/tests/groupby/test_index_as_string.py b/pandas/tests/groupby/test_index_as_string.py
index 4aaf3de9a23b2..743db7e70b14b 100644
--- a/pandas/tests/groupby/test_index_as_string.py
+++ b/pandas/tests/groupby/test_index_as_string.py
@@ -5,38 +5,6 @@
import pandas._testing as tm
-@pytest.fixture(params=[["inner"], ["inner", "outer"]])
-def frame(request):
- levels = request.param
- df = pd.DataFrame(
- {
- "outer": ["a", "a", "a", "b", "b", "b"],
- "inner": [1, 2, 3, 1, 2, 3],
- "A": np.arange(6),
- "B": ["one", "one", "two", "two", "one", "one"],
- }
- )
- if levels:
- df = df.set_index(levels)
-
- return df
-
-
-@pytest.fixture()
-def series():
- df = pd.DataFrame(
- {
- "outer": ["a", "a", "a", "b", "b", "b"],
- "inner": [1, 2, 3, 1, 2, 3],
- "A": np.arange(6),
- "B": ["one", "one", "two", "two", "one", "one"],
- }
- )
- s = df.set_index(["outer", "inner", "B"])["A"]
-
- return s
-
-
@pytest.mark.parametrize(
"key_strs,groupers",
[
@@ -46,7 +14,17 @@ def series():
(["inner", "B"], [pd.Grouper(level="inner"), "B"]), # Index and column
],
)
-def test_grouper_index_level_as_string(frame, key_strs, groupers):
+@pytest.mark.parametrize("levels", [["inner"], ["inner", "outer"]])
+def test_grouper_index_level_as_string(levels, key_strs, groupers):
+ frame = pd.DataFrame(
+ {
+ "outer": ["a", "a", "a", "b", "b", "b"],
+ "inner": [1, 2, 3, 1, 2, 3],
+ "A": np.arange(6),
+ "B": ["one", "one", "two", "two", "one", "one"],
+ }
+ )
+ frame = frame.set_index(levels)
if "B" not in key_strs or "outer" in frame.columns:
result = frame.groupby(key_strs).mean(numeric_only=True)
expected = frame.groupby(groupers).mean(numeric_only=True)
@@ -71,8 +49,17 @@ def test_grouper_index_level_as_string(frame, key_strs, groupers):
["B", "outer", "inner"],
],
)
-def test_grouper_index_level_as_string_series(series, levels):
+def test_grouper_index_level_as_string_series(levels):
# Compute expected result
+ df = pd.DataFrame(
+ {
+ "outer": ["a", "a", "a", "b", "b", "b"],
+ "inner": [1, 2, 3, 1, 2, 3],
+ "A": np.arange(6),
+ "B": ["one", "one", "two", "two", "one", "one"],
+ }
+ )
+ series = df.set_index(["outer", "inner", "B"])["A"]
if isinstance(levels, list):
groupers = [pd.Grouper(level=lv) for lv in levels]
else:
diff --git a/pandas/tests/groupby/test_indexing.py b/pandas/tests/groupby/test_indexing.py
index 664c52babac13..f839bf156ca00 100644
--- a/pandas/tests/groupby/test_indexing.py
+++ b/pandas/tests/groupby/test_indexing.py
@@ -118,15 +118,26 @@ def test_doc_examples():
tm.assert_frame_equal(result, expected)
-@pytest.fixture()
-def multiindex_data():
+def test_multiindex():
+ # Test the multiindex mentioned as the use-case in the documentation
+
+ def _make_df_from_data(data):
+ rows = {}
+ for date in data:
+ for level in data[date]:
+ rows[(date, level[0])] = {"A": level[1], "B": level[2]}
+
+ df = pd.DataFrame.from_dict(rows, orient="index")
+ df.index.names = ("Date", "Item")
+ return df
+
rng = np.random.default_rng(2)
ndates = 100
nitems = 20
dates = pd.date_range("20130101", periods=ndates, freq="D")
items = [f"item {i}" for i in range(nitems)]
- data = {}
+ multiindex_data = {}
for date in dates:
nitems_for_date = nitems - rng.integers(0, 12)
levels = [
@@ -134,28 +145,12 @@ def multiindex_data():
for item in items[:nitems_for_date]
]
levels.sort(key=lambda x: x[1])
- data[date] = levels
-
- return data
-
+ multiindex_data[date] = levels
-def _make_df_from_data(data):
- rows = {}
- for date in data:
- for level in data[date]:
- rows[(date, level[0])] = {"A": level[1], "B": level[2]}
-
- df = pd.DataFrame.from_dict(rows, orient="index")
- df.index.names = ("Date", "Item")
- return df
-
-
-def test_multiindex(multiindex_data):
- # Test the multiindex mentioned as the use-case in the documentation
df = _make_df_from_data(multiindex_data)
result = df.groupby("Date", as_index=False).nth(slice(3, -3))
- sliced = {date: multiindex_data[date][3:-3] for date in multiindex_data}
+ sliced = {date: values[3:-3] for date, values in multiindex_data.items()}
expected = _make_df_from_data(sliced)
tm.assert_frame_equal(result, expected)
@@ -271,15 +266,11 @@ def test_step(step):
tm.assert_frame_equal(result, expected)
-@pytest.fixture()
-def column_group_df():
- return pd.DataFrame(
+def test_column_axis():
+ column_group_df = pd.DataFrame(
[[0, 1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 0, 2]],
columns=["A", "B", "C", "D", "E", "F", "G"],
)
-
-
-def test_column_axis(column_group_df):
msg = "DataFrame.groupby with axis=1"
with tm.assert_produces_warning(FutureWarning, match=msg):
g = column_group_df.groupby(column_group_df.iloc[1], axis=1)
diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py
index 0b451ce73db89..738711019b5fd 100644
--- a/pandas/tests/groupby/test_raises.py
+++ b/pandas/tests/groupby/test_raises.py
@@ -67,19 +67,6 @@ def df_with_datetime_col():
return df
-@pytest.fixture
-def df_with_timedelta_col():
- df = DataFrame(
- {
- "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
- "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
- "c": range(9),
- "d": datetime.timedelta(days=1),
- }
- )
- return df
-
-
@pytest.fixture
def df_with_cat_col():
df = DataFrame(
@@ -353,8 +340,15 @@ def test_groupby_raises_datetime_np(
@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"])
-def test_groupby_raises_timedelta(func, df_with_timedelta_col):
- df = df_with_timedelta_col
+def test_groupby_raises_timedelta(func):
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.timedelta(days=1),
+ }
+ )
gb = df.groupby(by="a")
_call_and_check(
diff --git a/pandas/tests/indexes/datetimelike_/test_nat.py b/pandas/tests/indexes/datetimelike_/test_nat.py
index 50cf29d016355..3dd0ce1cbd637 100644
--- a/pandas/tests/indexes/datetimelike_/test_nat.py
+++ b/pandas/tests/indexes/datetimelike_/test_nat.py
@@ -10,44 +10,33 @@
import pandas._testing as tm
-class NATests:
- def test_nat(self, index_without_na):
- empty_index = index_without_na[:0]
-
- index_with_na = index_without_na.copy(deep=True)
- index_with_na._data[1] = NaT
-
- assert empty_index._na_value is NaT
- assert index_with_na._na_value is NaT
- assert index_without_na._na_value is NaT
-
- idx = index_without_na
- assert idx._can_hold_na
-
- tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
- assert idx.hasnans is False
-
- idx = index_with_na
- assert idx._can_hold_na
-
- tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
- assert idx.hasnans is True
+@pytest.mark.parametrize(
+ "index_without_na",
+ [
+ TimedeltaIndex(["1 days", "2 days"]),
+ PeriodIndex(["2011-01-01", "2011-01-02"], freq="D"),
+ DatetimeIndex(["2011-01-01", "2011-01-02"]),
+ DatetimeIndex(["2011-01-01", "2011-01-02"], tz="UTC"),
+ ],
+)
+def test_nat(index_without_na):
+ empty_index = index_without_na[:0]
+ index_with_na = index_without_na.copy(deep=True)
+ index_with_na._data[1] = NaT
-class TestDatetimeIndexNA(NATests):
- @pytest.fixture
- def index_without_na(self, tz_naive_fixture):
- tz = tz_naive_fixture
- return DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
+ assert empty_index._na_value is NaT
+ assert index_with_na._na_value is NaT
+ assert index_without_na._na_value is NaT
+ idx = index_without_na
+ assert idx._can_hold_na
-class TestTimedeltaIndexNA(NATests):
- @pytest.fixture
- def index_without_na(self):
- return TimedeltaIndex(["1 days", "2 days"])
+ tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
+ assert idx.hasnans is False
+ idx = index_with_na
+ assert idx._can_hold_na
-class TestPeriodIndexNA(NATests):
- @pytest.fixture
- def index_without_na(self):
- return PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")
+ tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
+ assert idx.hasnans is True
diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py
index 778c07b46e57c..e9864723f026e 100644
--- a/pandas/tests/indexes/interval/test_constructors.py
+++ b/pandas/tests/indexes/interval/test_constructors.py
@@ -23,11 +23,6 @@
import pandas.core.common as com
-@pytest.fixture(params=[None, "foo"])
-def name(request):
- return request.param
-
-
class ConstructorTests:
"""
Common tests for all variations of IntervalIndex construction. Input data
@@ -35,8 +30,9 @@ class ConstructorTests:
get_kwargs_from_breaks to the expected format.
"""
- @pytest.fixture(
- params=[
+ @pytest.mark.parametrize(
+ "breaks_and_expected_subtype",
+ [
([3, 14, 15, 92, 653], np.int64),
(np.arange(10, dtype="int64"), np.int64),
(Index(np.arange(-10, 11, dtype=np.int64)), np.int64),
@@ -48,11 +44,9 @@ class ConstructorTests:
"datetime64[ns, US/Eastern]",
),
(timedelta_range("1 day", periods=10), "<m8[ns]"),
- ]
+ ],
)
- def breaks_and_expected_subtype(self, request):
- return request.param
-
+ @pytest.mark.parametrize("name", [None, "foo"])
def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name):
breaks, expected_subtype = breaks_and_expected_subtype
@@ -372,14 +366,6 @@ def test_na_tuples(self):
class TestClassConstructors(ConstructorTests):
"""Tests specific to the IntervalIndex/Index constructors"""
- @pytest.fixture(
- params=[IntervalIndex, partial(Index, dtype="interval")],
- ids=["IntervalIndex", "Index"],
- )
- def klass(self, request):
- # We use a separate fixture here to include Index.__new__ with dtype kwarg
- return request.param
-
@pytest.fixture
def constructor(self):
return IntervalIndex
@@ -418,6 +404,11 @@ def test_constructor_string(self):
# the interval of strings is already forbidden.
pass
+ @pytest.mark.parametrize(
+ "klass",
+ [IntervalIndex, partial(Index, dtype="interval")],
+ ids=["IntervalIndex", "Index"],
+ )
def test_constructor_errors(self, klass):
# mismatched closed within intervals with no constructor override
ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")]
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 89b991318be0d..7391d39bdde7b 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -21,11 +21,6 @@
import pandas.core.common as com
-@pytest.fixture(params=[None, "foo"])
-def name(request):
- return request.param
-
-
class TestIntervalIndex:
index = IntervalIndex.from_arrays([0, 1], [1, 2])
@@ -865,6 +860,7 @@ def test_nbytes(self):
expected = 64 # 4 * 8 * 2
assert result == expected
+ @pytest.mark.parametrize("name", [None, "foo"])
def test_set_closed(self, name, closed, other_closed):
# GH 21670
index = interval_range(0, 5, closed=closed, name=name)
diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py
index 45b25f2533afd..49b17f8b3d40e 100644
--- a/pandas/tests/indexes/interval/test_interval_tree.py
+++ b/pandas/tests/indexes/interval/test_interval_tree.py
@@ -18,11 +18,6 @@ def skipif_32bit(param):
return pytest.param(param, marks=marks)
-@pytest.fixture(params=["int64", "float64", "uint64"])
-def dtype(request):
- return request.param
-
-
@pytest.fixture(params=[skipif_32bit(1), skipif_32bit(2), 10])
def leaf_size(request):
"""
@@ -103,6 +98,7 @@ def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype
expected_missing = np.array([0], dtype="intp")
tm.assert_numpy_array_equal(result_missing, expected_missing)
+ @pytest.mark.parametrize("dtype", ["int64", "float64", "uint64"])
def test_duplicates(self, dtype):
left = np.array([0, 0, 0], dtype=dtype)
tree = IntervalTree(left, left + 1)
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index cd28d519313ed..f2458a6c6114d 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -17,13 +17,6 @@
)
-@pytest.fixture
-def index_large():
- # large values used in Index[uint64] tests where no compat needed with Int64/Float64
- large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
- return Index(large, dtype=np.uint64)
-
-
class TestGetLoc:
def test_get_loc(self):
index = Index([0, 1, 2])
@@ -303,7 +296,11 @@ def test_get_indexer_int64(self):
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
- def test_get_indexer_uint64(self, index_large):
+ def test_get_indexer_uint64(self):
+ index_large = Index(
+ [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25],
+ dtype=np.uint64,
+ )
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target)
expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index dc5a6719284a6..4416034795463 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -15,12 +15,16 @@ def dtype(self, request):
return request.param
@pytest.fixture
- def simple_index(self, dtype):
- values = np.arange(5, dtype=dtype)
- return Index(values)
+ def mixed_index(self, dtype):
+ return Index([1.5, 2, 3, 4, 5], dtype=dtype)
+
+ @pytest.fixture
+ def float_index(self, dtype):
+ return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
- @pytest.fixture(
- params=[
+ @pytest.mark.parametrize(
+ "index_data",
+ [
[1.5, 2, 3, 4, 5],
[0.0, 2.5, 5.0, 7.5, 10.0],
[5, 4, 3, 2, 1.5],
@@ -28,18 +32,8 @@ def simple_index(self, dtype):
],
ids=["mixed", "float", "mixed_dec", "float_dec"],
)
- def index(self, request, dtype):
- return Index(request.param, dtype=dtype)
-
- @pytest.fixture
- def mixed_index(self, dtype):
- return Index([1.5, 2, 3, 4, 5], dtype=dtype)
-
- @pytest.fixture
- def float_index(self, dtype):
- return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
-
- def test_repr_roundtrip(self, index):
+ def test_repr_roundtrip(self, index_data, dtype):
+ index = Index(index_data, dtype=dtype)
tm.assert_index_equal(eval(repr(index)), index, exact=True)
def check_coerce(self, a, b, is_float_index=True):
@@ -227,8 +221,8 @@ def test_fillna_float64(self):
exp = Index([1.0, "obj", 3.0], name="x")
tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
- def test_logical_compat(self, simple_index):
- idx = simple_index
+ def test_logical_compat(self, dtype):
+ idx = Index(np.arange(5, dtype=dtype))
assert idx.all() == idx.values.all()
assert idx.any() == idx.values.any()
diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py
index 376b51dd98bb1..102560852e8e4 100644
--- a/pandas/tests/indexes/numeric/test_setops.py
+++ b/pandas/tests/indexes/numeric/test_setops.py
@@ -96,7 +96,11 @@ def test_float64_index_difference(self):
result = string_index.difference(float_index)
tm.assert_index_equal(result, string_index)
- def test_intersection_uint64_outside_int64_range(self, index_large):
+ def test_intersection_uint64_outside_int64_range(self):
+ index_large = Index(
+ [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25],
+ dtype=np.uint64,
+ )
other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20])
result = index_large.intersection(other)
expected = Index(np.sort(np.intersect1d(index_large.values, other.values)))
diff --git a/pandas/tests/indexing/conftest.py b/pandas/tests/indexing/conftest.py
deleted file mode 100644
index 4184c6a0047cc..0000000000000
--- a/pandas/tests/indexing/conftest.py
+++ /dev/null
@@ -1,127 +0,0 @@
-import numpy as np
-import pytest
-
-from pandas import (
- DataFrame,
- Index,
- MultiIndex,
- Series,
- date_range,
-)
-
-
-@pytest.fixture
-def series_ints():
- return Series(np.random.default_rng(2).random(4), index=np.arange(0, 8, 2))
-
-
-@pytest.fixture
-def frame_ints():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=np.arange(0, 8, 2),
- columns=np.arange(0, 12, 3),
- )
-
-
-@pytest.fixture
-def series_uints():
- return Series(
- np.random.default_rng(2).random(4),
- index=Index(np.arange(0, 8, 2, dtype=np.uint64)),
- )
-
-
-@pytest.fixture
-def frame_uints():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=Index(range(0, 8, 2), dtype=np.uint64),
- columns=Index(range(0, 12, 3), dtype=np.uint64),
- )
-
-
-@pytest.fixture
-def series_labels():
- return Series(np.random.default_rng(2).standard_normal(4), index=list("abcd"))
-
-
-@pytest.fixture
-def frame_labels():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=list("abcd"),
- columns=list("ABCD"),
- )
-
-
-@pytest.fixture
-def series_ts():
- return Series(
- np.random.default_rng(2).standard_normal(4),
- index=date_range("20130101", periods=4),
- )
-
-
-@pytest.fixture
-def frame_ts():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=date_range("20130101", periods=4),
- )
-
-
-@pytest.fixture
-def series_floats():
- return Series(
- np.random.default_rng(2).random(4),
- index=Index(range(0, 8, 2), dtype=np.float64),
- )
-
-
-@pytest.fixture
-def frame_floats():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=Index(range(0, 8, 2), dtype=np.float64),
- columns=Index(range(0, 12, 3), dtype=np.float64),
- )
-
-
-@pytest.fixture
-def series_mixed():
- return Series(np.random.default_rng(2).standard_normal(4), index=[2, 4, "null", 8])
-
-
-@pytest.fixture
-def frame_mixed():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)), index=[2, 4, "null", 8]
- )
-
-
-@pytest.fixture
-def frame_empty():
- return DataFrame()
-
-
-@pytest.fixture
-def series_empty():
- return Series(dtype=object)
-
-
-@pytest.fixture
-def frame_multi():
- return DataFrame(
- np.random.default_rng(2).standard_normal((4, 4)),
- index=MultiIndex.from_product([[1, 2], [3, 4]]),
- columns=MultiIndex.from_product([[5, 6], [7, 8]]),
- )
-
-
-@pytest.fixture
-def series_multi():
- return Series(
- np.random.default_rng(2).random(4),
- index=MultiIndex.from_product([[1, 2], [3, 4]]),
- )
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 5508153322adb..de7d644698f2c 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -16,14 +16,6 @@
import pandas._testing as tm
-@pytest.fixture
-def single_level_multiindex():
- """single level MultiIndex"""
- return MultiIndex(
- levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"]
- )
-
-
@pytest.fixture
def frame_random_data_integer_multi_index():
levels = [[0, 1], [0, 1, 2]]
@@ -277,8 +269,10 @@ def test_loc_multiindex_incomplete(self):
result = s.loc[2:4:2, "a":"c"]
tm.assert_series_equal(result, expected)
- def test_get_loc_single_level(self, single_level_multiindex):
- single_level = single_level_multiindex
+ def test_get_loc_single_level(self):
+ single_level = MultiIndex(
+ levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"]
+ )
s = Series(
np.random.default_rng(2).standard_normal(len(single_level)),
index=single_level,
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index 13d786f98c42b..e0898a636474c 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -38,13 +38,18 @@
class TestiLoc:
@pytest.mark.parametrize("key", [2, -1, [0, 1, 2]])
- @pytest.mark.parametrize("kind", ["series", "frame"])
@pytest.mark.parametrize(
- "col",
- ["labels", "mixed", "ts", "floats", "empty"],
+ "index",
+ [
+ Index(list("abcd"), dtype=object),
+ Index([2, 4, "null", 8], dtype=object),
+ date_range("20130101", periods=4),
+ Index(range(0, 8, 2), dtype=np.float64),
+ Index([]),
+ ],
)
- def test_iloc_getitem_int_and_list_int(self, key, kind, col, request):
- obj = request.getfixturevalue(f"{kind}_{col}")
+ def test_iloc_getitem_int_and_list_int(self, key, frame_or_series, index, request):
+ obj = frame_or_series(range(len(index)), index=index)
check_indexing_smoketest_or_raises(
obj,
"iloc",
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index ada6f88679673..c455b0bc8599b 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -68,116 +68,111 @@ def test_none_values_on_string_columns(self):
assert df.loc[2, "a"] is None
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_int(self, kind, request):
+ def test_loc_getitem_int(self, frame_or_series):
# int label
- obj = request.getfixturevalue(f"{kind}_labels")
+ obj = frame_or_series(range(3), index=Index(list("abc"), dtype=object))
check_indexing_smoketest_or_raises(obj, "loc", 2, fails=KeyError)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label(self, kind, request):
+ def test_loc_getitem_label(self, frame_or_series):
# label
- obj = request.getfixturevalue(f"{kind}_empty")
+ obj = frame_or_series()
check_indexing_smoketest_or_raises(obj, "loc", "c", fails=KeyError)
+ @pytest.mark.parametrize("key", ["f", 20])
@pytest.mark.parametrize(
- "key, typs, axes",
+ "index",
[
- ["f", ["ints", "uints", "labels", "mixed", "ts"], None],
- ["f", ["floats"], None],
- [20, ["ints", "uints", "mixed"], None],
- [20, ["labels"], None],
- [20, ["ts"], 0],
- [20, ["floats"], 0],
+ Index(list("abcd"), dtype=object),
+ Index([2, 4, "null", 8], dtype=object),
+ date_range("20130101", periods=4),
+ Index(range(0, 8, 2), dtype=np.float64),
+ Index([]),
],
)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label_out_of_range(self, key, typs, axes, kind, request):
- for typ in typs:
- obj = request.getfixturevalue(f"{kind}_{typ}")
- # out of range label
- check_indexing_smoketest_or_raises(
- obj, "loc", key, axes=axes, fails=KeyError
- )
+ def test_loc_getitem_label_out_of_range(self, key, index, frame_or_series):
+ obj = frame_or_series(range(len(index)), index=index)
+ # out of range label
+ check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError)
+
+ @pytest.mark.parametrize("key", [[0, 1, 2], [1, 3.0, "A"]])
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])
+ def test_loc_getitem_label_list(self, key, dtype, frame_or_series):
+ obj = frame_or_series(range(3), index=Index([0, 1, 2], dtype=dtype))
+ # list of labels
+ check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError)
@pytest.mark.parametrize(
- "key, typs",
+ "index",
[
- [[0, 1, 2], ["ints", "uints", "floats"]],
- [[1, 3.0, "A"], ["ints", "uints", "floats"]],
+ None,
+ Index([0, 1, 2], dtype=np.int64),
+ Index([0, 1, 2], dtype=np.uint64),
+ Index([0, 1, 2], dtype=np.float64),
+ MultiIndex.from_arrays([range(3), range(3)]),
],
)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label_list(self, key, typs, kind, request):
- for typ in typs:
- obj = request.getfixturevalue(f"{kind}_{typ}")
- # list of labels
- check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError)
-
@pytest.mark.parametrize(
- "key, typs, axes",
- [
- [[0, 1, 2], ["empty"], None],
- [[0, 2, 10], ["ints", "uints", "floats"], 0],
- [[3, 6, 7], ["ints", "uints", "floats"], 1],
- # GH 17758 - MultiIndex and missing keys
- [[(1, 3), (1, 4), (2, 5)], ["multi"], 0],
- ],
+ "key", [[0, 1, 2], [0, 2, 10], [3, 6, 7], [(1, 3), (1, 4), (2, 5)]]
)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label_list_with_missing(self, key, typs, axes, kind, request):
- for typ in typs:
- obj = request.getfixturevalue(f"{kind}_{typ}")
- check_indexing_smoketest_or_raises(
- obj, "loc", key, axes=axes, fails=KeyError
- )
+ def test_loc_getitem_label_list_with_missing(self, key, index, frame_or_series):
+ if index is None:
+ obj = frame_or_series()
+ else:
+ obj = frame_or_series(range(len(index)), index=index)
+ check_indexing_smoketest_or_raises(obj, "loc", key, fails=KeyError)
- @pytest.mark.parametrize("typs", ["ints", "uints"])
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label_list_fails(self, typs, kind, request):
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64])
+ def test_loc_getitem_label_list_fails(self, dtype, frame_or_series):
# fails
- obj = request.getfixturevalue(f"{kind}_{typs}")
+ obj = frame_or_series(range(3), Index([0, 1, 2], dtype=dtype))
check_indexing_smoketest_or_raises(
obj, "loc", [20, 30, 40], axes=1, fails=KeyError
)
- def test_loc_getitem_label_array_like(self):
- # TODO: test something?
- # array like
- pass
-
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_bool(self, kind, request):
- obj = request.getfixturevalue(f"{kind}_empty")
+ def test_loc_getitem_bool(self, frame_or_series):
+ obj = frame_or_series()
# boolean indexers
b = [True, False, True, False]
check_indexing_smoketest_or_raises(obj, "loc", b, fails=IndexError)
@pytest.mark.parametrize(
- "slc, typs, axes, fails",
+ "slc, indexes, axes, fails",
[
[
slice(1, 3),
- ["labels", "mixed", "empty", "ts", "floats"],
+ [
+ Index(list("abcd"), dtype=object),
+ Index([2, 4, "null", 8], dtype=object),
+ None,
+ date_range("20130101", periods=4),
+ Index(range(0, 12, 3), dtype=np.float64),
+ ],
None,
TypeError,
],
- [slice("20130102", "20130104"), ["ts"], 1, TypeError],
- [slice(2, 8), ["mixed"], 0, TypeError],
- [slice(2, 8), ["mixed"], 1, KeyError],
- [slice(2, 4, 2), ["mixed"], 0, TypeError],
+ [
+ slice("20130102", "20130104"),
+ [date_range("20130101", periods=4)],
+ 1,
+ TypeError,
+ ],
+ [slice(2, 8), [Index([2, 4, "null", 8], dtype=object)], 0, TypeError],
+ [slice(2, 8), [Index([2, 4, "null", 8], dtype=object)], 1, KeyError],
+ [slice(2, 4, 2), [Index([2, 4, "null", 8], dtype=object)], 0, TypeError],
],
)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- def test_loc_getitem_label_slice(self, slc, typs, axes, fails, kind, request):
+ def test_loc_getitem_label_slice(self, slc, indexes, axes, fails, frame_or_series):
# label slices (with ints)
# real label slices
# GH 14316
- for typ in typs:
- obj = request.getfixturevalue(f"{kind}_{typ}")
+ for index in indexes:
+ if index is None:
+ obj = frame_or_series()
+ else:
+ obj = frame_or_series(range(len(index)), index=index)
check_indexing_smoketest_or_raises(
obj,
"loc",
diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py
index 29e3dc0aebe95..ef4cd402aaf24 100644
--- a/pandas/tests/indexing/test_scalar.py
+++ b/pandas/tests/indexing/test_scalar.py
@@ -10,6 +10,7 @@
from pandas import (
DataFrame,
+ Index,
Series,
Timedelta,
Timestamp,
@@ -32,29 +33,42 @@ def generate_indices(f, values=False):
class TestScalar:
- @pytest.mark.parametrize("kind", ["series", "frame"])
- @pytest.mark.parametrize("col", ["ints", "uints"])
- def test_iat_set_ints(self, kind, col, request):
- f = request.getfixturevalue(f"{kind}_{col}")
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64])
+ def test_iat_set_ints(self, dtype, frame_or_series):
+ f = frame_or_series(range(3), index=Index([0, 1, 2], dtype=dtype))
indices = generate_indices(f, True)
for i in indices:
f.iat[i] = 1
expected = f.values[i]
tm.assert_almost_equal(expected, 1)
- @pytest.mark.parametrize("kind", ["series", "frame"])
- @pytest.mark.parametrize("col", ["labels", "ts", "floats"])
- def test_iat_set_other(self, kind, col, request):
- f = request.getfixturevalue(f"{kind}_{col}")
+ @pytest.mark.parametrize(
+ "index",
+ [
+ Index(list("abcd"), dtype=object),
+ date_range("20130101", periods=4),
+ Index(range(0, 8, 2), dtype=np.float64),
+ ],
+ )
+ def test_iat_set_other(self, index, frame_or_series):
+ f = frame_or_series(range(len(index)), index=index)
msg = "iAt based indexing can only have integer indexers"
with pytest.raises(ValueError, match=msg):
idx = next(generate_indices(f, False))
f.iat[idx] = 1
- @pytest.mark.parametrize("kind", ["series", "frame"])
- @pytest.mark.parametrize("col", ["ints", "uints", "labels", "ts", "floats"])
- def test_at_set_ints_other(self, kind, col, request):
- f = request.getfixturevalue(f"{kind}_{col}")
+ @pytest.mark.parametrize(
+ "index",
+ [
+ Index(list("abcd"), dtype=object),
+ date_range("20130101", periods=4),
+ Index(range(0, 8, 2), dtype=np.float64),
+ Index(range(0, 8, 2), dtype=np.uint64),
+ Index(range(0, 8, 2), dtype=np.int64),
+ ],
+ )
+ def test_at_set_ints_other(self, index, frame_or_series):
+ f = frame_or_series(range(len(index)), index=index)
indices = generate_indices(f, False)
for i in indices:
f.at[i] = 1
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index 8bc6b48922a4f..6d8cc501ade6c 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -21,29 +21,12 @@
from pandas.core.interchange.utils import ArrowCTypes
-@pytest.fixture
-def data_categorical():
- return {
+@pytest.mark.parametrize("data", [("ordered", True), ("unordered", False)])
+def test_categorical_dtype(data):
+ data_categorical = {
"ordered": pd.Categorical(list("testdata") * 30, ordered=True),
"unordered": pd.Categorical(list("testdata") * 30, ordered=False),
}
-
-
-@pytest.fixture
-def string_data():
- return {
- "separator data": [
- "abC|DeF,Hik",
- "234,3245.67",
- "gSaf,qWer|Gre",
- "asd3,4sad|",
- np.nan,
- ]
- }
-
-
-@pytest.mark.parametrize("data", [("ordered", True), ("unordered", False)])
-def test_categorical_dtype(data, data_categorical):
df = pd.DataFrame({"A": (data_categorical[data[0]])})
col = df.__dataframe__().get_column_by_name("A")
@@ -231,7 +214,16 @@ def test_mixed_missing():
assert df2.get_column_by_name(col_name).null_count == 2
-def test_string(string_data):
+def test_string():
+ string_data = {
+ "separator data": [
+ "abC|DeF,Hik",
+ "234,3245.67",
+ "gSaf,qWer|Gre",
+ "asd3,4sad|",
+ np.nan,
+ ]
+ }
test_str_data = string_data["separator data"] + [""]
df = pd.DataFrame({"A": test_str_data})
col = df.__dataframe__().get_column_by_name("A")
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index 0ca29c219b55b..43e94b8c55589 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -4,7 +4,6 @@
"""
from datetime import datetime
from io import StringIO
-from pathlib import Path
import re
from shutil import get_terminal_size
@@ -32,55 +31,6 @@
import pandas.io.formats.format as fmt
-@pytest.fixture(params=["string", "pathlike", "buffer"])
-def filepath_or_buffer_id(request):
- """
- A fixture yielding test ids for filepath_or_buffer testing.
- """
- return request.param
-
-
-@pytest.fixture
-def filepath_or_buffer(filepath_or_buffer_id, tmp_path):
- """
- A fixture yielding a string representing a filepath, a path-like object
- and a StringIO buffer. Also checks that buffer is not closed.
- """
- if filepath_or_buffer_id == "buffer":
- buf = StringIO()
- yield buf
- assert not buf.closed
- else:
- assert isinstance(tmp_path, Path)
- if filepath_or_buffer_id == "pathlike":
- yield tmp_path / "foo"
- else:
- yield str(tmp_path / "foo")
-
-
-@pytest.fixture
-def assert_filepath_or_buffer_equals(
- filepath_or_buffer, filepath_or_buffer_id, encoding
-):
- """
- Assertion helper for checking filepath_or_buffer.
- """
- if encoding is None:
- encoding = "utf-8"
-
- def _assert_filepath_or_buffer_equals(expected):
- if filepath_or_buffer_id == "string":
- with open(filepath_or_buffer, encoding=encoding) as f:
- result = f.read()
- elif filepath_or_buffer_id == "pathlike":
- result = filepath_or_buffer.read_text(encoding=encoding)
- elif filepath_or_buffer_id == "buffer":
- result = filepath_or_buffer.getvalue()
- assert result == expected
-
- return _assert_filepath_or_buffer_equals
-
-
def has_info_repr(df):
r = repr(df)
c1 = r.split("\n")[0].startswith("<class")
@@ -2258,14 +2208,21 @@ def test_format_percentiles_integer_idx(self):
"encoding, data",
[(None, "abc"), ("utf-8", "abc"), ("gbk", "造成输出中文显示乱码"), ("foo", "abc")],
)
+@pytest.mark.parametrize("filepath_or_buffer_id", ["string", "pathlike", "buffer"])
def test_filepath_or_buffer_arg(
method,
- filepath_or_buffer,
- assert_filepath_or_buffer_equals,
+ tmp_path,
encoding,
data,
filepath_or_buffer_id,
):
+ if filepath_or_buffer_id == "buffer":
+ filepath_or_buffer = StringIO()
+ elif filepath_or_buffer_id == "pathlike":
+ filepath_or_buffer = tmp_path / "foo"
+ else:
+ filepath_or_buffer = str(tmp_path / "foo")
+
df = DataFrame([data])
if method in ["to_latex"]: # uses styler implementation
pytest.importorskip("jinja2")
@@ -2281,7 +2238,17 @@ def test_filepath_or_buffer_arg(
else:
expected = getattr(df, method)()
getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
- assert_filepath_or_buffer_equals(expected)
+ encoding = encoding or "utf-8"
+ if filepath_or_buffer_id == "string":
+ with open(filepath_or_buffer, encoding=encoding) as f:
+ result = f.read()
+ elif filepath_or_buffer_id == "pathlike":
+ result = filepath_or_buffer.read_text(encoding=encoding)
+ elif filepath_or_buffer_id == "buffer":
+ result = filepath_or_buffer.getvalue()
+ assert result == expected
+ if filepath_or_buffer_id == "buffer":
+ assert not filepath_or_buffer.closed
@pytest.mark.parametrize("method", ["to_string", "to_html", "to_latex"])
diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
index b7bb057bc538e..015b27d0b3606 100644
--- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
+++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
@@ -132,17 +132,6 @@ def sa(self):
def ia(self):
return array([10], dtype="Int64")
- @pytest.fixture
- def df(self, da, dc, sa, ia):
- return DataFrame(
- {
- "A": da,
- "B": dc,
- "C": sa,
- "D": ia,
- }
- )
-
def test_build_date_series(self, da):
s = Series(da, name="a")
s.index.name = "id"
@@ -243,8 +232,15 @@ def test_build_int64_series(self, ia):
assert result == expected
- def test_to_json(self, df):
- df = df.copy()
+ def test_to_json(self, da, dc, sa, ia):
+ df = DataFrame(
+ {
+ "A": da,
+ "B": dc,
+ "C": sa,
+ "D": ia,
+ }
+ )
df.index.name = "idx"
result = df.to_json(orient="table", date_format="iso")
result = json.loads(result, object_pairs_hook=OrderedDict)
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py
index 3c6517a872b76..7914d40ea8aaa 100644
--- a/pandas/tests/io/json/test_normalize.py
+++ b/pandas/tests/io/json/test_normalize.py
@@ -78,17 +78,6 @@ def state_data():
]
-@pytest.fixture
-def author_missing_data():
- return [
- {"info": None},
- {
- "info": {"created_at": "11/08/1993", "last_updated": "26/05/2012"},
- "author_name": {"first": "Jane", "last_name": "Doe"},
- },
- ]
-
-
@pytest.fixture
def missing_metadata():
return [
@@ -120,23 +109,6 @@ def missing_metadata():
]
-@pytest.fixture
-def max_level_test_input_data():
- """
- input data to test json_normalize with max_level param
- """
- return [
- {
- "CreatedBy": {"Name": "User001"},
- "Lookup": {
- "TextField": "Some text",
- "UserField": {"Id": "ID001", "Name": "Name001"},
- },
- "Image": {"a": "b"},
- }
- ]
-
-
class TestJSONNormalize:
def test_simple_records(self):
recs = [
@@ -424,8 +396,15 @@ def test_non_ascii_key(self):
result = json_normalize(json.loads(testjson))
tm.assert_frame_equal(result, expected)
- def test_missing_field(self, author_missing_data):
+ def test_missing_field(self):
# GH20030:
+ author_missing_data = [
+ {"info": None},
+ {
+ "info": {"created_at": "11/08/1993", "last_updated": "26/05/2012"},
+ "author_name": {"first": "Jane", "last_name": "Doe"},
+ },
+ ]
result = json_normalize(author_missing_data)
ex_data = [
{
@@ -843,8 +822,18 @@ def test_nonetype_multiple_levels(self):
),
],
)
- def test_with_max_level(self, max_level, expected, max_level_test_input_data):
+ def test_with_max_level(self, max_level, expected):
# GH23843: Enhanced JSON normalize
+ max_level_test_input_data = [
+ {
+ "CreatedBy": {"Name": "User001"},
+ "Lookup": {
+ "TextField": "Some text",
+ "UserField": {"Id": "ID001", "Name": "Name001"},
+ },
+ "Image": {"a": "b"},
+ }
+ ]
output = nested_to_record(max_level_test_input_data, max_level=max_level)
assert output == expected
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 9fa46222bce1a..7254fd7cb345d 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -93,17 +93,6 @@ def assert_json_roundtrip_equal(result, expected, orient):
class TestPandasContainer:
- @pytest.fixture
- def categorical_frame(self):
- data = {
- c: np.random.default_rng(i).standard_normal(30)
- for i, c in enumerate(list("ABCD"))
- }
- cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * 15
- data["E"] = list(reversed(cat))
- data["sort"] = np.arange(30, dtype="int64")
- return DataFrame(data, index=pd.CategoricalIndex(cat, name="E"))
-
@pytest.fixture
def datetime_series(self):
# Same as usual datetime_series, but with index freq set to None,
@@ -249,7 +238,7 @@ def test_roundtrip_str_axes(self, orient, convert_axes, dtype):
@pytest.mark.parametrize("convert_axes", [True, False])
def test_roundtrip_categorical(
- self, request, orient, categorical_frame, convert_axes, using_infer_string
+ self, request, orient, convert_axes, using_infer_string
):
# TODO: create a better frame to test with and improve coverage
if orient in ("index", "columns"):
@@ -259,6 +248,14 @@ def test_roundtrip_categorical(
)
)
+ data = {
+ c: np.random.default_rng(i).standard_normal(30)
+ for i, c in enumerate(list("ABCD"))
+ }
+ cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * 15
+ data["E"] = list(reversed(cat))
+ data["sort"] = np.arange(30, dtype="int64")
+ categorical_frame = DataFrame(data, index=pd.CategoricalIndex(cat, name="E"))
data = StringIO(categorical_frame.to_json(orient=orient))
result = read_json(data, orient=orient, convert_axes=convert_axes)
diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py
index 766c9c37d55b9..30ca70d7e0009 100644
--- a/pandas/tests/io/sas/test_xport.py
+++ b/pandas/tests/io/sas/test_xport.py
@@ -19,31 +19,12 @@ def numeric_as_float(data):
class TestXport:
- @pytest.fixture
- def file01(self, datapath):
- return datapath("io", "sas", "data", "DEMO_G.xpt")
-
- @pytest.fixture
- def file02(self, datapath):
- return datapath("io", "sas", "data", "SSHSV1_A.xpt")
-
- @pytest.fixture
- def file03(self, datapath):
- return datapath("io", "sas", "data", "DRXFCD_G.xpt")
-
- @pytest.fixture
- def file04(self, datapath):
- return datapath("io", "sas", "data", "paxraw_d_short.xpt")
-
- @pytest.fixture
- def file05(self, datapath):
- return datapath("io", "sas", "data", "DEMO_PUF.cpt")
-
@pytest.mark.slow
- def test1_basic(self, file01):
+ def test1_basic(self, datapath):
# Tests with DEMO_G.xpt (all numeric file)
# Compare to this
+ file01 = datapath("io", "sas", "data", "DEMO_G.xpt")
data_csv = pd.read_csv(file01.replace(".xpt", ".csv"))
numeric_as_float(data_csv)
@@ -78,10 +59,11 @@ def test1_basic(self, file01):
data = read_sas(file01)
tm.assert_frame_equal(data, data_csv)
- def test1_index(self, file01):
+ def test1_index(self, datapath):
# Tests with DEMO_G.xpt using index (all numeric file)
# Compare to this
+ file01 = datapath("io", "sas", "data", "DEMO_G.xpt")
data_csv = pd.read_csv(file01.replace(".xpt", ".csv"))
data_csv = data_csv.set_index("SEQN")
numeric_as_float(data_csv)
@@ -100,9 +82,10 @@ def test1_index(self, file01):
data = reader.get_chunk()
tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False)
- def test1_incremental(self, file01):
+ def test1_incremental(self, datapath):
# Test with DEMO_G.xpt, reading full file incrementally
+ file01 = datapath("io", "sas", "data", "DEMO_G.xpt")
data_csv = pd.read_csv(file01.replace(".xpt", ".csv"))
data_csv = data_csv.set_index("SEQN")
numeric_as_float(data_csv)
@@ -113,9 +96,10 @@ def test1_incremental(self, file01):
tm.assert_frame_equal(data, data_csv, check_index_type=False)
- def test2(self, file02):
+ def test2(self, datapath):
# Test with SSHSV1_A.xpt
+ file02 = datapath("io", "sas", "data", "SSHSV1_A.xpt")
# Compare to this
data_csv = pd.read_csv(file02.replace(".xpt", ".csv"))
numeric_as_float(data_csv)
@@ -123,10 +107,11 @@ def test2(self, file02):
data = read_sas(file02)
tm.assert_frame_equal(data, data_csv)
- def test2_binary(self, file02):
+ def test2_binary(self, datapath):
# Test with SSHSV1_A.xpt, read as a binary file
# Compare to this
+ file02 = datapath("io", "sas", "data", "SSHSV1_A.xpt")
data_csv = pd.read_csv(file02.replace(".xpt", ".csv"))
numeric_as_float(data_csv)
@@ -137,31 +122,32 @@ def test2_binary(self, file02):
tm.assert_frame_equal(data, data_csv)
- def test_multiple_types(self, file03):
+ def test_multiple_types(self, datapath):
# Test with DRXFCD_G.xpt (contains text and numeric variables)
# Compare to this
+ file03 = datapath("io", "sas", "data", "DRXFCD_G.xpt")
data_csv = pd.read_csv(file03.replace(".xpt", ".csv"))
data = read_sas(file03, encoding="utf-8")
tm.assert_frame_equal(data, data_csv)
- def test_truncated_float_support(self, file04):
+ def test_truncated_float_support(self, datapath):
# Test with paxraw_d_short.xpt, a shortened version of:
# http://wwwn.cdc.gov/Nchs/Nhanes/2005-2006/PAXRAW_D.ZIP
# This file has truncated floats (5 bytes in this case).
# GH 11713
-
+ file04 = datapath("io", "sas", "data", "paxraw_d_short.xpt")
data_csv = pd.read_csv(file04.replace(".xpt", ".csv"))
data = read_sas(file04, format="xport")
tm.assert_frame_equal(data.astype("int64"), data_csv)
- def test_cport_header_found_raises(self, file05):
+ def test_cport_header_found_raises(self, datapath):
# Test with DEMO_PUF.cpt, the beginning of puf2019_1_fall.xpt
# from https://www.cms.gov/files/zip/puf2019.zip
# (despite the extension, it's a cpt file)
msg = "Header record indicates a CPORT file, which is not readable."
with pytest.raises(ValueError, match=msg):
- read_sas(file05, format="xport")
+ read_sas(datapath("io", "sas", "data", "DEMO_PUF.cpt"), format="xport")
diff --git a/pandas/tests/io/test_orc.py b/pandas/tests/io/test_orc.py
index a4021311fc963..b4a8c713d99ab 100644
--- a/pandas/tests/io/test_orc.py
+++ b/pandas/tests/io/test_orc.py
@@ -27,21 +27,6 @@ def dirpath(datapath):
return datapath("io", "data", "orc")
-@pytest.fixture(
- params=[
- np.array([1, 20], dtype="uint64"),
- pd.Series(["a", "b", "a"], dtype="category"),
- [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)],
- [pd.Period("2022-01-03", freq="D"), pd.Period("2022-01-04", freq="D")],
- ]
-)
-def orc_writer_dtypes_not_supported(request):
- # Examples of dataframes with dtypes for which conversion to ORC
- # hasn't been implemented yet, that is, Category, unsigned integers,
- # interval, period and sparse.
- return pd.DataFrame({"unimpl": request.param})
-
-
def test_orc_reader_empty(dirpath):
columns = [
"boolean1",
@@ -294,14 +279,24 @@ def test_orc_roundtrip_bytesio():
tm.assert_equal(expected, got)
+@pytest.mark.parametrize(
+ "orc_writer_dtypes_not_supported",
+ [
+ np.array([1, 20], dtype="uint64"),
+ pd.Series(["a", "b", "a"], dtype="category"),
+ [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)],
+ [pd.Period("2022-01-03", freq="D"), pd.Period("2022-01-04", freq="D")],
+ ],
+)
def test_orc_writer_dtypes_not_supported(orc_writer_dtypes_not_supported):
# GH44554
# PyArrow gained ORC write support with the current argument order
pytest.importorskip("pyarrow")
+ df = pd.DataFrame({"unimpl": orc_writer_dtypes_not_supported})
msg = "The dtype of one or more columns is not supported yet."
with pytest.raises(NotImplementedError, match=msg):
- orc_writer_dtypes_not_supported.to_orc()
+ df.to_orc()
def test_orc_dtype_backend_pyarrow():
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index e6488bcc4568f..21a38c43f4294 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -44,54 +44,6 @@ def get_test_data(ngroups=8, n=50):
return arr
-def get_series():
- return [
- Series([1], dtype="int64"),
- Series([1], dtype="Int64"),
- Series([1.23]),
- Series(["foo"]),
- Series([True]),
- Series([pd.Timestamp("2018-01-01")]),
- Series([pd.Timestamp("2018-01-01", tz="US/Eastern")]),
- ]
-
-
-def get_series_na():
- return [
- Series([np.nan], dtype="Int64"),
- Series([np.nan], dtype="float"),
- Series([np.nan], dtype="object"),
- Series([pd.NaT]),
- ]
-
-
-@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
-def series_of_dtype(request):
- """
- A parametrized fixture returning a variety of Series of different
- dtypes
- """
- return request.param
-
-
-@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
-def series_of_dtype2(request):
- """
- A duplicate of the series_of_dtype fixture, so that it can be used
- twice by a single function
- """
- return request.param
-
-
-@pytest.fixture(params=get_series_na(), ids=lambda x: x.dtype.name)
-def series_of_dtype_all_na(request):
- """
- A parametrized fixture returning a variety of Series with all NA
- values
- """
- return request.param
-
-
@pytest.fixture
def dfs_for_indicator():
df1 = DataFrame({"col1": [0, 1], "col_conflict": [1, 2], "col_left": ["a", "b"]})
@@ -140,13 +92,6 @@ def left(self):
}
)
- @pytest.fixture
- def right(self):
- return DataFrame(
- {"v2": np.random.default_rng(2).standard_normal(4)},
- index=["d", "b", "c", "a"],
- )
-
def test_merge_inner_join_empty(self):
# GH 15328
df_empty = DataFrame()
@@ -230,7 +175,11 @@ def test_merge_index_singlekey_inner(self):
expected = left.join(right, on="key").loc[result.index]
tm.assert_frame_equal(result, expected.loc[:, result.columns])
- def test_merge_misspecified(self, df, df2, left, right):
+ def test_merge_misspecified(self, df, df2, left):
+ right = DataFrame(
+ {"v2": np.random.default_rng(2).standard_normal(4)},
+ index=["d", "b", "c", "a"],
+ )
msg = "Must pass right_on or right_index=True"
with pytest.raises(pd.errors.MergeError, match=msg):
merge(left, right, left_index=True)
@@ -571,6 +520,30 @@ def check2(exp, kwarg):
check1(exp_in, kwarg)
check2(exp_out, kwarg)
+ @pytest.mark.parametrize(
+ "series_of_dtype",
+ [
+ Series([1], dtype="int64"),
+ Series([1], dtype="Int64"),
+ Series([1.23]),
+ Series(["foo"]),
+ Series([True]),
+ Series([pd.Timestamp("2018-01-01")]),
+ Series([pd.Timestamp("2018-01-01", tz="US/Eastern")]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "series_of_dtype2",
+ [
+ Series([1], dtype="int64"),
+ Series([1], dtype="Int64"),
+ Series([1.23]),
+ Series(["foo"]),
+ Series([True]),
+ Series([pd.Timestamp("2018-01-01")]),
+ Series([pd.Timestamp("2018-01-01", tz="US/Eastern")]),
+ ],
+ )
def test_merge_empty_frame(self, series_of_dtype, series_of_dtype2):
# GH 25183
df = DataFrame(
@@ -589,6 +562,27 @@ def test_merge_empty_frame(self, series_of_dtype, series_of_dtype2):
actual = df_empty.merge(df, on="key")
tm.assert_frame_equal(actual, expected)
+ @pytest.mark.parametrize(
+ "series_of_dtype",
+ [
+ Series([1], dtype="int64"),
+ Series([1], dtype="Int64"),
+ Series([1.23]),
+ Series(["foo"]),
+ Series([True]),
+ Series([pd.Timestamp("2018-01-01")]),
+ Series([pd.Timestamp("2018-01-01", tz="US/Eastern")]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "series_of_dtype_all_na",
+ [
+ Series([np.nan], dtype="Int64"),
+ Series([np.nan], dtype="float"),
+ Series([np.nan], dtype="object"),
+ Series([pd.NaT]),
+ ],
+ )
def test_merge_all_na_column(self, series_of_dtype, series_of_dtype_all_na):
# GH 25183
df_left = DataFrame(
@@ -2134,16 +2128,6 @@ def test_merge_on_int_array(self):
tm.assert_frame_equal(result, expected)
-@pytest.fixture
-def left_df():
- return DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
-
-
-@pytest.fixture
-def right_df():
- return DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
-
-
class TestMergeOnIndexes:
@pytest.mark.parametrize(
"how, sort, expected",
@@ -2192,7 +2176,9 @@ class TestMergeOnIndexes:
),
],
)
- def test_merge_on_indexes(self, left_df, right_df, how, sort, expected):
+ def test_merge_on_indexes(self, how, sort, expected):
+ left_df = DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
+ right_df = DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
result = merge(
left_df, right_df, left_index=True, right_index=True, how=how, sort=sort
)
diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py
index 33502f576dd2f..00df8064d5190 100644
--- a/pandas/tests/reshape/merge/test_merge_asof.py
+++ b/pandas/tests/reshape/merge/test_merge_asof.py
@@ -604,486 +604,6 @@ def tolerance(self):
df["ask"] = df["ask"].astype("float64")
return self.prep_data(df)
- @pytest.fixture
- def allow_exact_matches(self, datapath):
- df = pd.DataFrame(
- [
- [
- "20160525 13:30:00.023",
- "MSFT",
- "51.95",
- "75",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.038",
- "MSFT",
- "51.95",
- "155",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.77",
- "100",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.92",
- "100",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "200",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "300",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "600",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "44",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.074",
- "AAPL",
- "98.67",
- "478343",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.67",
- "478343",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.66",
- "6",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "30",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "75",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "20",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "35",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "10",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
- ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "1000",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "200",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "300",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "400",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "600",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "200",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "783",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "100",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "100",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- ],
- columns="time,ticker,price,quantity,marketCenter,bid,ask".split(","),
- )
- df["price"] = df["price"].astype("float64")
- df["quantity"] = df["quantity"].astype("int64")
- df["bid"] = df["bid"].astype("float64")
- df["ask"] = df["ask"].astype("float64")
- return self.prep_data(df)
-
- @pytest.fixture
- def allow_exact_matches_and_tolerance(self):
- df = pd.DataFrame(
- [
- [
- "20160525 13:30:00.023",
- "MSFT",
- "51.95",
- "75",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.038",
- "MSFT",
- "51.95",
- "155",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.77",
- "100",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.92",
- "100",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "200",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "300",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "600",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.048",
- "GOOG",
- "720.93",
- "44",
- "NASDAQ",
- "720.5",
- "720.93",
- ],
- [
- "20160525 13:30:00.074",
- "AAPL",
- "98.67",
- "478343",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.67",
- "478343",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.66",
- "6",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "30",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "75",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "20",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "35",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- [
- "20160525 13:30:00.075",
- "AAPL",
- "98.65",
- "10",
- "NASDAQ",
- np.nan,
- np.nan,
- ],
- ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
- ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "1000",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "200",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "300",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "400",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "600",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.076",
- "AAPL",
- "98.56",
- "200",
- "ARCA",
- "98.55",
- "98.56",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "783",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "100",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- [
- "20160525 13:30:00.078",
- "MSFT",
- "51.95",
- "100",
- "NASDAQ",
- "51.95",
- "51.95",
- ],
- ],
- columns="time,ticker,price,quantity,marketCenter,bid,ask".split(","),
- )
- df["price"] = df["price"].astype("float64")
- df["quantity"] = df["quantity"].astype("int64")
- df["bid"] = df["bid"].astype("float64")
- df["ask"] = df["ask"].astype("float64")
- return self.prep_data(df)
-
def test_examples1(self):
"""doc-string examples"""
left = pd.DataFrame({"a": [1, 5, 10], "left_val": ["a", "b", "c"]})
@@ -2620,11 +2140,247 @@ def test_index_tolerance(self, trades, quotes, tolerance):
)
tm.assert_frame_equal(result, expected)
- def test_allow_exact_matches(self, trades, quotes, allow_exact_matches):
+ def test_allow_exact_matches(self, trades, quotes):
result = merge_asof(
trades, quotes, on="time", by="ticker", allow_exact_matches=False
)
- expected = allow_exact_matches
+ df = pd.DataFrame(
+ [
+ [
+ "20160525 13:30:00.023",
+ "MSFT",
+ "51.95",
+ "75",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.038",
+ "MSFT",
+ "51.95",
+ "155",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.77",
+ "100",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.92",
+ "100",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "200",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "300",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "600",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "44",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.074",
+ "AAPL",
+ "98.67",
+ "478343",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.67",
+ "478343",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.66",
+ "6",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "30",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "75",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "20",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "35",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "10",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
+ ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "1000",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "200",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "300",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "400",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "600",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "200",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "783",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "100",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "100",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ ],
+ columns="time,ticker,price,quantity,marketCenter,bid,ask".split(","),
+ )
+ df["price"] = df["price"].astype("float64")
+ df["quantity"] = df["quantity"].astype("int64")
+ df["bid"] = df["bid"].astype("float64")
+ df["ask"] = df["ask"].astype("float64")
+ expected = self.prep_data(df)
tm.assert_frame_equal(result, expected)
def test_allow_exact_matches_forward(self):
@@ -2657,9 +2413,7 @@ def test_allow_exact_matches_nearest(self):
)
tm.assert_frame_equal(result, expected)
- def test_allow_exact_matches_and_tolerance(
- self, trades, quotes, allow_exact_matches_and_tolerance
- ):
+ def test_allow_exact_matches_and_tolerance(self, trades, quotes):
result = merge_asof(
trades,
quotes,
@@ -2668,7 +2422,243 @@ def test_allow_exact_matches_and_tolerance(
tolerance=Timedelta("100ms"),
allow_exact_matches=False,
)
- expected = allow_exact_matches_and_tolerance
+ df = pd.DataFrame(
+ [
+ [
+ "20160525 13:30:00.023",
+ "MSFT",
+ "51.95",
+ "75",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.038",
+ "MSFT",
+ "51.95",
+ "155",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.77",
+ "100",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.92",
+ "100",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "200",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "300",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "600",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.048",
+ "GOOG",
+ "720.93",
+ "44",
+ "NASDAQ",
+ "720.5",
+ "720.93",
+ ],
+ [
+ "20160525 13:30:00.074",
+ "AAPL",
+ "98.67",
+ "478343",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.67",
+ "478343",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.66",
+ "6",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "30",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "75",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "20",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "35",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ [
+ "20160525 13:30:00.075",
+ "AAPL",
+ "98.65",
+ "10",
+ "NASDAQ",
+ np.nan,
+ np.nan,
+ ],
+ ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
+ ["20160525 13:30:00.075", "AAPL", "98.55", "6", "ARCA", np.nan, np.nan],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "1000",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "200",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "300",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "400",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "600",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.076",
+ "AAPL",
+ "98.56",
+ "200",
+ "ARCA",
+ "98.55",
+ "98.56",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "783",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "100",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ [
+ "20160525 13:30:00.078",
+ "MSFT",
+ "51.95",
+ "100",
+ "NASDAQ",
+ "51.95",
+ "51.95",
+ ],
+ ],
+ columns="time,ticker,price,quantity,marketCenter,bid,ask".split(","),
+ )
+ df["price"] = df["price"].astype("float64")
+ df["quantity"] = df["quantity"].astype("int64")
+ df["bid"] = df["bid"].astype("float64")
+ df["ask"] = df["ask"].astype("float64")
+ expected = self.prep_data(df)
tm.assert_frame_equal(result, expected)
def test_allow_exact_matches_and_tolerance2(self):
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 6564ac0fd7e8a..af156a1da87f2 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -30,12 +30,6 @@
from pandas.core.reshape.pivot import pivot_table
-@pytest.fixture(params=[([0] * 4, [1] * 4), (range(3), range(1, 4))])
-def interval_values(request, closed):
- left, right = request.param
- return Categorical(pd.IntervalIndex.from_arrays(left, right, closed))
-
-
class TestPivotTable:
@pytest.fixture
def data(self):
@@ -303,8 +297,13 @@ def test_pivot_with_non_observable_dropna_multi_cat(self, dropna):
tm.assert_frame_equal(result, expected)
- def test_pivot_with_interval_index(self, interval_values, dropna):
+ @pytest.mark.parametrize(
+ "left_right", [([0] * 4, [1] * 4), (range(3), range(1, 4))]
+ )
+ def test_pivot_with_interval_index(self, left_right, dropna, closed):
# GH 25814
+ left, right = left_right
+ interval_values = Categorical(pd.IntervalIndex.from_arrays(left, right, closed))
df = DataFrame({"A": interval_values, "B": 1})
msg = "The default value of observed=False is deprecated"
diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py
index b0a920ba02cad..f6f3a3b0fb07e 100644
--- a/pandas/tests/series/methods/test_convert_dtypes.py
+++ b/pandas/tests/series/methods/test_convert_dtypes.py
@@ -8,187 +8,180 @@
import pandas as pd
import pandas._testing as tm
-# Each test case consists of a tuple with the data and dtype to create the
-# test Series, the default dtype for the expected result (which is valid
-# for most cases), and the specific cases where the result deviates from
-# this default. Those overrides are defined as a dict with (keyword, val) as
-# dictionary key. In case of multiple items, the last override takes precedence.
-
-
-@pytest.fixture(
- params=[
- (
- # data
- [1, 2, 3],
- # original dtype
- np.dtype("int32"),
- # default expected dtype
- "Int32",
- # exceptions on expected dtype
- {("convert_integer", False): np.dtype("int32")},
- ),
- (
- [1, 2, 3],
- np.dtype("int64"),
- "Int64",
- {("convert_integer", False): np.dtype("int64")},
- ),
- (
- ["x", "y", "z"],
- np.dtype("O"),
- pd.StringDtype(),
- {("convert_string", False): np.dtype("O")},
- ),
- (
- [True, False, np.nan],
- np.dtype("O"),
- pd.BooleanDtype(),
- {("convert_boolean", False): np.dtype("O")},
- ),
- (
- ["h", "i", np.nan],
- np.dtype("O"),
- pd.StringDtype(),
- {("convert_string", False): np.dtype("O")},
- ),
- ( # GH32117
- ["h", "i", 1],
- np.dtype("O"),
- np.dtype("O"),
- {},
- ),
- (
- [10, np.nan, 20],
- np.dtype("float"),
- "Int64",
- {
- ("convert_integer", False, "convert_floating", True): "Float64",
- ("convert_integer", False, "convert_floating", False): np.dtype(
- "float"
- ),
- },
- ),
- (
- [np.nan, 100.5, 200],
- np.dtype("float"),
- "Float64",
- {("convert_floating", False): np.dtype("float")},
- ),
- (
- [3, 4, 5],
- "Int8",
- "Int8",
- {},
- ),
- (
- [[1, 2], [3, 4], [5]],
- None,
- np.dtype("O"),
- {},
- ),
- (
- [4, 5, 6],
- np.dtype("uint32"),
- "UInt32",
- {("convert_integer", False): np.dtype("uint32")},
- ),
- (
- [-10, 12, 13],
- np.dtype("i1"),
- "Int8",
- {("convert_integer", False): np.dtype("i1")},
- ),
- (
- [1.2, 1.3],
- np.dtype("float32"),
- "Float32",
- {("convert_floating", False): np.dtype("float32")},
- ),
- (
- [1, 2.0],
- object,
- "Int64",
- {
- ("convert_integer", False): "Float64",
- ("convert_integer", False, "convert_floating", False): np.dtype(
- "float"
- ),
- ("infer_objects", False): np.dtype("object"),
- },
- ),
- (
- [1, 2.5],
- object,
- "Float64",
- {
- ("convert_floating", False): np.dtype("float"),
- ("infer_objects", False): np.dtype("object"),
- },
- ),
- (["a", "b"], pd.CategoricalDtype(), pd.CategoricalDtype(), {}),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("s"),
- pd.DatetimeTZDtype(tz="UTC"),
- pd.DatetimeTZDtype(tz="UTC"),
- {},
- ),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ms"),
- pd.DatetimeTZDtype(tz="UTC"),
- pd.DatetimeTZDtype(tz="UTC"),
- {},
- ),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("us"),
- pd.DatetimeTZDtype(tz="UTC"),
- pd.DatetimeTZDtype(tz="UTC"),
- {},
- ),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
- pd.DatetimeTZDtype(tz="UTC"),
- pd.DatetimeTZDtype(tz="UTC"),
- {},
- ),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
- "datetime64[ns]",
- np.dtype("datetime64[ns]"),
- {},
- ),
- (
- pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
- object,
- np.dtype("datetime64[ns]"),
- {("infer_objects", False): np.dtype("object")},
- ),
- (
- pd.period_range("1/1/2011", freq="M", periods=3),
- None,
- pd.PeriodDtype("M"),
- {},
- ),
- (
- pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]),
- None,
- pd.IntervalDtype("int64", "right"),
- {},
- ),
- ]
-)
-def test_cases(request):
- return request.param
-
class TestSeriesConvertDtypes:
+ @pytest.mark.parametrize(
+ "data, maindtype, expected_default, expected_other",
+ [
+ (
+ # data
+ [1, 2, 3],
+ # original dtype
+ np.dtype("int32"),
+ # default expected dtype
+ "Int32",
+ # exceptions on expected dtype
+ {("convert_integer", False): np.dtype("int32")},
+ ),
+ (
+ [1, 2, 3],
+ np.dtype("int64"),
+ "Int64",
+ {("convert_integer", False): np.dtype("int64")},
+ ),
+ (
+ ["x", "y", "z"],
+ np.dtype("O"),
+ pd.StringDtype(),
+ {("convert_string", False): np.dtype("O")},
+ ),
+ (
+ [True, False, np.nan],
+ np.dtype("O"),
+ pd.BooleanDtype(),
+ {("convert_boolean", False): np.dtype("O")},
+ ),
+ (
+ ["h", "i", np.nan],
+ np.dtype("O"),
+ pd.StringDtype(),
+ {("convert_string", False): np.dtype("O")},
+ ),
+ ( # GH32117
+ ["h", "i", 1],
+ np.dtype("O"),
+ np.dtype("O"),
+ {},
+ ),
+ (
+ [10, np.nan, 20],
+ np.dtype("float"),
+ "Int64",
+ {
+ ("convert_integer", False, "convert_floating", True): "Float64",
+ ("convert_integer", False, "convert_floating", False): np.dtype(
+ "float"
+ ),
+ },
+ ),
+ (
+ [np.nan, 100.5, 200],
+ np.dtype("float"),
+ "Float64",
+ {("convert_floating", False): np.dtype("float")},
+ ),
+ (
+ [3, 4, 5],
+ "Int8",
+ "Int8",
+ {},
+ ),
+ (
+ [[1, 2], [3, 4], [5]],
+ None,
+ np.dtype("O"),
+ {},
+ ),
+ (
+ [4, 5, 6],
+ np.dtype("uint32"),
+ "UInt32",
+ {("convert_integer", False): np.dtype("uint32")},
+ ),
+ (
+ [-10, 12, 13],
+ np.dtype("i1"),
+ "Int8",
+ {("convert_integer", False): np.dtype("i1")},
+ ),
+ (
+ [1.2, 1.3],
+ np.dtype("float32"),
+ "Float32",
+ {("convert_floating", False): np.dtype("float32")},
+ ),
+ (
+ [1, 2.0],
+ object,
+ "Int64",
+ {
+ ("convert_integer", False): "Float64",
+ ("convert_integer", False, "convert_floating", False): np.dtype(
+ "float"
+ ),
+ ("infer_objects", False): np.dtype("object"),
+ },
+ ),
+ (
+ [1, 2.5],
+ object,
+ "Float64",
+ {
+ ("convert_floating", False): np.dtype("float"),
+ ("infer_objects", False): np.dtype("object"),
+ },
+ ),
+ (["a", "b"], pd.CategoricalDtype(), pd.CategoricalDtype(), {}),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("s"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ms"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("us"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
+ "datetime64[ns]",
+ np.dtype("datetime64[ns]"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"),
+ object,
+ np.dtype("datetime64[ns]"),
+ {("infer_objects", False): np.dtype("object")},
+ ),
+ (
+ pd.period_range("1/1/2011", freq="M", periods=3),
+ None,
+ pd.PeriodDtype("M"),
+ {},
+ ),
+ (
+ pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]),
+ None,
+ pd.IntervalDtype("int64", "right"),
+ {},
+ ),
+ ],
+ )
@pytest.mark.parametrize("params", product(*[(True, False)] * 5))
def test_convert_dtypes(
self,
- test_cases,
+ data,
+ maindtype,
+ expected_default,
+ expected_other,
params,
using_infer_string,
):
- data, maindtype, expected_default, expected_other = test_cases
if (
hasattr(data, "dtype")
and lib.is_np_dtype(data.dtype, "M")
diff --git a/pandas/tests/series/methods/test_nlargest.py b/pandas/tests/series/methods/test_nlargest.py
index e8de1cd89e397..bf13ea04ca9f9 100644
--- a/pandas/tests/series/methods/test_nlargest.py
+++ b/pandas/tests/series/methods/test_nlargest.py
@@ -2,8 +2,6 @@
Note: for naming purposes, most tests are title with as e.g. "test_nlargest_foo"
but are implicitly also testing nsmallest_foo.
"""
-from itertools import product
-
import numpy as np
import pytest
@@ -11,68 +9,6 @@
from pandas import Series
import pandas._testing as tm
-main_dtypes = [
- "datetime",
- "datetimetz",
- "timedelta",
- "int8",
- "int16",
- "int32",
- "int64",
- "float32",
- "float64",
- "uint8",
- "uint16",
- "uint32",
- "uint64",
-]
-
-
-@pytest.fixture
-def s_main_dtypes():
- """
- A DataFrame with many dtypes
-
- * datetime
- * datetimetz
- * timedelta
- * [u]int{8,16,32,64}
- * float{32,64}
-
- The columns are the name of the dtype.
- """
- df = pd.DataFrame(
- {
- "datetime": pd.to_datetime(["2003", "2002", "2001", "2002", "2005"]),
- "datetimetz": pd.to_datetime(
- ["2003", "2002", "2001", "2002", "2005"]
- ).tz_localize("US/Eastern"),
- "timedelta": pd.to_timedelta(["3d", "2d", "1d", "2d", "5d"]),
- }
- )
-
- for dtype in [
- "int8",
- "int16",
- "int32",
- "int64",
- "float32",
- "float64",
- "uint8",
- "uint16",
- "uint32",
- "uint64",
- ]:
- df[dtype] = Series([3, 2, 1, 2, 5], dtype=dtype)
-
- return df
-
-
-@pytest.fixture(params=main_dtypes)
-def s_main_dtypes_split(request, s_main_dtypes):
- """Each series in s_main_dtypes."""
- return s_main_dtypes[request.param]
-
def assert_check_nselect_boundary(vals, dtype, method):
# helper function for 'test_boundary_{dtype}' tests
@@ -96,19 +32,36 @@ class TestSeriesNLargestNSmallest:
Series(list("abcde"), dtype="category"),
],
)
- def test_nlargest_error(self, r):
+ @pytest.mark.parametrize("method", ["nlargest", "nsmallest"])
+ @pytest.mark.parametrize("arg", [2, 5, 0, -1])
+ def test_nlargest_error(self, r, method, arg):
dt = r.dtype
msg = f"Cannot use method 'n(largest|smallest)' with dtype {dt}"
- args = 2, len(r), 0, -1
- methods = r.nlargest, r.nsmallest
- for method, arg in product(methods, args):
- with pytest.raises(TypeError, match=msg):
- method(arg)
+ with pytest.raises(TypeError, match=msg):
+ getattr(r, method)(arg)
- def test_nsmallest_nlargest(self, s_main_dtypes_split):
+ @pytest.mark.parametrize(
+ "data",
+ [
+ pd.to_datetime(["2003", "2002", "2001", "2002", "2005"]),
+ pd.to_datetime(["2003", "2002", "2001", "2002", "2005"], utc=True),
+ pd.to_timedelta(["3d", "2d", "1d", "2d", "5d"]),
+ np.array([3, 2, 1, 2, 5], dtype="int8"),
+ np.array([3, 2, 1, 2, 5], dtype="int16"),
+ np.array([3, 2, 1, 2, 5], dtype="int32"),
+ np.array([3, 2, 1, 2, 5], dtype="int64"),
+ np.array([3, 2, 1, 2, 5], dtype="uint8"),
+ np.array([3, 2, 1, 2, 5], dtype="uint16"),
+ np.array([3, 2, 1, 2, 5], dtype="uint32"),
+ np.array([3, 2, 1, 2, 5], dtype="uint64"),
+ np.array([3, 2, 1, 2, 5], dtype="float32"),
+ np.array([3, 2, 1, 2, 5], dtype="float64"),
+ ],
+ )
+ def test_nsmallest_nlargest(self, data):
# float, int, datetime64 (use i8), timedelts64 (same),
# object that are numbers, object that are strings
- ser = s_main_dtypes_split
+ ser = Series(data)
tm.assert_series_equal(ser.nsmallest(2), ser.iloc[[2, 1]])
tm.assert_series_equal(ser.nsmallest(2, keep="last"), ser.iloc[[2, 3]])
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 51ce73ef54300..10776fe5d050f 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -2,6 +2,7 @@
Testing that we work in the downstream packages
"""
import array
+from functools import partial
import subprocess
import sys
@@ -9,7 +10,6 @@
import pytest
from pandas.errors import IntCastingNaNError
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -261,46 +261,25 @@ def __radd__(self, other):
assert right + left is left
-@pytest.fixture(
- params=[
- "memoryview",
- "array",
- pytest.param("dask", marks=td.skip_if_no("dask.array")),
- pytest.param("xarray", marks=td.skip_if_no("xarray")),
- ]
-)
-def array_likes(request):
- """
- Fixture giving a numpy array and a parametrized 'data' object, which can
- be a memoryview, array, dask or xarray object created from the numpy array.
- """
- # GH#24539 recognize e.g xarray, dask, ...
- arr = np.array([1, 2, 3], dtype=np.int64)
-
- name = request.param
- if name == "memoryview":
- data = memoryview(arr)
- elif name == "array":
- data = array.array("i", arr)
- elif name == "dask":
- import dask.array
-
- data = dask.array.array(arr)
- elif name == "xarray":
- import xarray as xr
-
- data = xr.DataArray(arr)
-
- return arr, data
-
-
@pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
-def test_from_obscure_array(dtype, array_likes):
+@pytest.mark.parametrize(
+ "box", [memoryview, partial(array.array, "i"), "dask", "xarray"]
+)
+def test_from_obscure_array(dtype, box):
# GH#24539 recognize e.g xarray, dask, ...
# Note: we dont do this for PeriodArray bc _from_sequence won't accept
# an array of integers
# TODO: could check with arraylike of Period objects
- arr, data = array_likes
+ # GH#24539 recognize e.g xarray, dask, ...
+ arr = np.array([1, 2, 3], dtype=np.int64)
+ if box == "dask":
+ da = pytest.importorskip("dask.array")
+ data = da.array(arr)
+ elif box == "xarray":
+ xr = pytest.importorskip("xarray")
+ data = xr.DataArray(arr)
+ else:
+ data = box(arr)
cls = {"M8[ns]": DatetimeArray, "m8[ns]": TimedeltaArray}[dtype]
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 5b856bc632a1d..cb94427ae8961 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -3300,37 +3300,6 @@ def units(request):
return request.param
-@pytest.fixture
-def epoch_1960():
- """Timestamp at 1960-01-01."""
- return Timestamp("1960-01-01")
-
-
-@pytest.fixture
-def units_from_epochs():
- return list(range(5))
-
-
-@pytest.fixture(params=["timestamp", "pydatetime", "datetime64", "str_1960"])
-def epochs(epoch_1960, request):
- """Timestamp at 1960-01-01 in various forms.
-
- * Timestamp
- * datetime.datetime
- * numpy.datetime64
- * str
- """
- assert request.param in {"timestamp", "pydatetime", "datetime64", "str_1960"}
- if request.param == "timestamp":
- return epoch_1960
- elif request.param == "pydatetime":
- return epoch_1960.to_pydatetime()
- elif request.param == "datetime64":
- return epoch_1960.to_datetime64()
- else:
- return str(epoch_1960)
-
-
@pytest.fixture
def julian_dates():
return date_range("2014-1-1", periods=10).to_julian_date().values
@@ -3388,7 +3357,18 @@ def test_invalid_origin(self, unit):
with pytest.raises(ValueError, match=msg):
to_datetime("2005-01-01", origin="1960-01-01", unit=unit)
- def test_epoch(self, units, epochs, epoch_1960, units_from_epochs):
+ @pytest.mark.parametrize(
+ "epochs",
+ [
+ Timestamp(1960, 1, 1),
+ datetime(1960, 1, 1),
+ "1960-01-01",
+ np.datetime64("1960-01-01"),
+ ],
+ )
+ def test_epoch(self, units, epochs):
+ epoch_1960 = Timestamp(1960, 1, 1)
+ units_from_epochs = list(range(5))
expected = Series(
[pd.Timedelta(x, unit=units) + epoch_1960 for x in units_from_epochs]
)
@@ -3405,7 +3385,7 @@ def test_epoch(self, units, epochs, epoch_1960, units_from_epochs):
(datetime(1, 1, 1), OutOfBoundsDatetime),
],
)
- def test_invalid_origins(self, origin, exc, units, units_from_epochs):
+ def test_invalid_origins(self, origin, exc, units):
msg = "|".join(
[
f"origin {origin} is Out of Bounds",
@@ -3414,7 +3394,7 @@ def test_invalid_origins(self, origin, exc, units, units_from_epochs):
]
)
with pytest.raises(exc, match=msg):
- to_datetime(units_from_epochs, unit=units, origin=origin)
+ to_datetime(list(range(5)), unit=units, origin=origin)
def test_invalid_origins_tzinfo(self):
# GH16842
diff --git a/pandas/tests/tseries/offsets/test_common.py b/pandas/tests/tseries/offsets/test_common.py
index aa4e22f71ad66..3792878973c15 100644
--- a/pandas/tests/tseries/offsets/test_common.py
+++ b/pandas/tests/tseries/offsets/test_common.py
@@ -106,15 +106,6 @@ def _offset(request):
return request.param
-@pytest.fixture
-def dt(_offset):
- if _offset in (CBMonthBegin, CBMonthEnd, BDay):
- return Timestamp(2008, 1, 1)
- elif _offset is (CustomBusinessHour, BusinessHour):
- return Timestamp(2014, 7, 1, 10, 00)
- return Timestamp(2008, 1, 2)
-
-
def test_apply_out_of_range(request, tz_naive_fixture, _offset):
tz = tz_naive_fixture
diff --git a/pandas/tests/tseries/offsets/test_custom_business_month.py b/pandas/tests/tseries/offsets/test_custom_business_month.py
index d226302e042d3..b74b210c3b191 100644
--- a/pandas/tests/tseries/offsets/test_custom_business_month.py
+++ b/pandas/tests/tseries/offsets/test_custom_business_month.py
@@ -62,30 +62,18 @@ def test_copy(self, _offset):
class TestCustomBusinessMonthBegin:
- @pytest.fixture
- def _offset(self):
- return CBMonthBegin
-
- @pytest.fixture
- def offset(self):
- return CBMonthBegin()
-
- @pytest.fixture
- def offset2(self):
- return CBMonthBegin(2)
-
- def test_different_normalize_equals(self, _offset):
+ def test_different_normalize_equals(self):
# GH#21404 changed __eq__ to return False when `normalize` does not match
- offset = _offset()
- offset2 = _offset(normalize=True)
+ offset = CBMonthBegin()
+ offset2 = CBMonthBegin(normalize=True)
assert offset != offset2
- def test_repr(self, offset, offset2):
- assert repr(offset) == "<CustomBusinessMonthBegin>"
- assert repr(offset2) == "<2 * CustomBusinessMonthBegins>"
+ def test_repr(self):
+ assert repr(CBMonthBegin()) == "<CustomBusinessMonthBegin>"
+ assert repr(CBMonthBegin(2)) == "<2 * CustomBusinessMonthBegins>"
- def test_add_datetime(self, dt, offset2):
- assert offset2 + dt == datetime(2008, 3, 3)
+ def test_add_datetime(self, dt):
+ assert CBMonthBegin(2) + dt == datetime(2008, 3, 3)
def testRollback1(self):
assert CDay(10).rollback(datetime(2007, 12, 31)) == datetime(2007, 12, 31)
@@ -252,30 +240,18 @@ def test_apply_with_extra_offset(self, case):
class TestCustomBusinessMonthEnd:
- @pytest.fixture
- def _offset(self):
- return CBMonthEnd
-
- @pytest.fixture
- def offset(self):
- return CBMonthEnd()
-
- @pytest.fixture
- def offset2(self):
- return CBMonthEnd(2)
-
- def test_different_normalize_equals(self, _offset):
+ def test_different_normalize_equals(self):
# GH#21404 changed __eq__ to return False when `normalize` does not match
- offset = _offset()
- offset2 = _offset(normalize=True)
+ offset = CBMonthEnd()
+ offset2 = CBMonthEnd(normalize=True)
assert offset != offset2
- def test_repr(self, offset, offset2):
- assert repr(offset) == "<CustomBusinessMonthEnd>"
- assert repr(offset2) == "<2 * CustomBusinessMonthEnds>"
+ def test_repr(self):
+ assert repr(CBMonthEnd()) == "<CustomBusinessMonthEnd>"
+ assert repr(CBMonthEnd(2)) == "<2 * CustomBusinessMonthEnds>"
- def test_add_datetime(self, dt, offset2):
- assert offset2 + dt == datetime(2008, 2, 29)
+ def test_add_datetime(self, dt):
+ assert CBMonthEnd(2) + dt == datetime(2008, 2, 29)
def testRollback1(self):
assert CDay(10).rollback(datetime(2007, 12, 31)) == datetime(2007, 12, 31)
diff --git a/pandas/tests/util/test_assert_produces_warning.py b/pandas/tests/util/test_assert_produces_warning.py
index 5c27a3ee79d4a..88e9f0d8fccee 100644
--- a/pandas/tests/util/test_assert_produces_warning.py
+++ b/pandas/tests/util/test_assert_produces_warning.py
@@ -13,26 +13,6 @@
import pandas._testing as tm
-@pytest.fixture(
- params=[
- RuntimeWarning,
- ResourceWarning,
- UserWarning,
- FutureWarning,
- DeprecationWarning,
- PerformanceWarning,
- DtypeWarning,
- ],
-)
-def category(request):
- """
- Return unique warning.
-
- Useful for testing behavior of tm.assert_produces_warning with various categories.
- """
- return request.param
-
-
@pytest.fixture(
params=[
(RuntimeWarning, UserWarning),
@@ -73,6 +53,18 @@ def test_assert_produces_warning_honors_filter():
f()
+@pytest.mark.parametrize(
+ "category",
+ [
+ RuntimeWarning,
+ ResourceWarning,
+ UserWarning,
+ FutureWarning,
+ DeprecationWarning,
+ PerformanceWarning,
+ DtypeWarning,
+ ],
+)
@pytest.mark.parametrize(
"message, match",
[
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56625 | 2023-12-26T19:42:27Z | 2024-01-03T00:49:57Z | 2024-01-03T00:49:57Z | 2024-01-03T00:50:00Z |
Backport PR #56617 on branch 2.2.x (TYP: some return types from ruff) | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2a070e9a49b97..7f3fc95ce00cc 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -32,6 +32,8 @@ repos:
# TODO: remove autofixe-only rules when they are checked by ruff
name: ruff-selected-autofixes
alias: ruff-selected-autofixes
+ files: ^pandas
+ exclude: ^pandas/tests
args: [--select, "ANN001,ANN2", --fix-only, --exit-non-zero-on-fix]
- repo: https://github.com/jendrikseipp/vulture
rev: 'v2.10'
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index d1481639ca5a0..5ee94b74c527e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -431,7 +431,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| Package | Minimum Version | Changed |
+=================+=================+=========+
-| mypy (dev) | 1.7.1 | X |
+| mypy (dev) | 1.8.0 | X |
+-----------------+-----------------+---------+
| | | X |
+-----------------+-----------------+---------+
diff --git a/environment.yml b/environment.yml
index 74317d47e2e53..58eb69ad1f070 100644
--- a/environment.yml
+++ b/environment.yml
@@ -76,7 +76,7 @@ dependencies:
# code checks
- flake8=6.1.0 # run in subprocess over docstring examples
- - mypy=1.7.1 # pre-commit uses locally installed mypy
+ - mypy=1.8.0 # pre-commit uses locally installed mypy
- tokenize-rt # scripts/check_for_inconsistent_pandas_namespace.py
- pre-commit>=3.6.0
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index e342f76dc724b..800b03707540f 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -4,6 +4,7 @@
from typing import (
TYPE_CHECKING,
Literal,
+ NoReturn,
cast,
)
@@ -143,7 +144,7 @@ def assert_almost_equal(
)
-def _check_isinstance(left, right, cls):
+def _check_isinstance(left, right, cls) -> None:
"""
Helper method for our assert_* methods that ensures that
the two objects being compared have the right type before
@@ -576,7 +577,7 @@ def assert_timedelta_array_equal(
def raise_assert_detail(
obj, message, left, right, diff=None, first_diff=None, index_values=None
-):
+) -> NoReturn:
__tracebackhide__ = True
msg = f"""{obj} are different
@@ -664,7 +665,7 @@ def _get_base(obj):
if left_base is right_base:
raise AssertionError(f"{repr(left_base)} is {repr(right_base)}")
- def _raise(left, right, err_msg):
+ def _raise(left, right, err_msg) -> NoReturn:
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(
diff --git a/pandas/_version.py b/pandas/_version.py
index 5d610b5e1ea7e..f8a960630126d 100644
--- a/pandas/_version.py
+++ b/pandas/_version.py
@@ -386,7 +386,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
return pieces
-def plus_or_dot(pieces):
+def plus_or_dot(pieces) -> str:
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index 4770f403b1bdb..b5861fbaebe9c 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -695,8 +695,8 @@ def visit_Call(self, node, side=None, **kwargs):
if not isinstance(key, ast.keyword):
# error: "expr" has no attribute "id"
raise ValueError(
- "keyword error in function call " # type: ignore[attr-defined]
- f"'{node.func.id}'"
+ "keyword error in function call "
+ f"'{node.func.id}'" # type: ignore[attr-defined]
)
if key.arg:
diff --git a/pandas/io/html.py b/pandas/io/html.py
index 5d5bf079784be..26e71c9546ffd 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -269,7 +269,7 @@ def _attr_getter(self, obj, attr):
# Both lxml and BeautifulSoup have the same implementation:
return obj.get(attr)
- def _href_getter(self, obj):
+ def _href_getter(self, obj) -> str | None:
"""
Return a href if the DOM node contains a child <a> or None.
@@ -392,7 +392,7 @@ def _parse_tables(self, document, match, attrs):
"""
raise AbstractMethodError(self)
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
"""
Return whether an individual DOM node matches a tag
@@ -629,7 +629,7 @@ def _href_getter(self, obj) -> str | None:
def _text_getter(self, obj):
return obj.text
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
return obj.name == tag
def _parse_td(self, row):
@@ -758,7 +758,7 @@ def _parse_tables(self, document, match, kwargs):
raise ValueError(f"No tables found matching regex {repr(pattern)}")
return tables
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
return obj.tag == tag
def _build_doc(self):
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index ed66e46b300f7..4c490c6b2cda2 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -255,7 +255,7 @@ def __init__(
self.is_copy = None
self._format_axes()
- def _format_axes(self):
+ def _format_axes(self) -> None:
raise AbstractMethodError(self)
def write(self) -> str:
@@ -287,7 +287,7 @@ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
else:
return self.obj
- def _format_axes(self):
+ def _format_axes(self) -> None:
if not self.obj.index.is_unique and self.orient == "index":
raise ValueError(f"Series index must be unique for orient='{self.orient}'")
@@ -304,7 +304,7 @@ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
obj_to_write = self.obj
return obj_to_write
- def _format_axes(self):
+ def _format_axes(self) -> None:
"""
Try to format axes if they are datelike.
"""
@@ -1193,7 +1193,7 @@ def parse(self):
self._try_convert_types()
return self.obj
- def _parse(self):
+ def _parse(self) -> None:
raise AbstractMethodError(self)
@final
@@ -1217,7 +1217,7 @@ def _convert_axes(self) -> None:
new_axis = Index(new_ser, dtype=new_ser.dtype, copy=False)
setattr(self.obj, axis_name, new_axis)
- def _try_convert_types(self):
+ def _try_convert_types(self) -> None:
raise AbstractMethodError(self)
@final
diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py
index 66a7ccacf675b..890b22154648e 100644
--- a/pandas/io/parsers/arrow_parser_wrapper.py
+++ b/pandas/io/parsers/arrow_parser_wrapper.py
@@ -41,7 +41,7 @@ def __init__(self, src: ReadBuffer[bytes], **kwds) -> None:
self._parse_kwds()
- def _parse_kwds(self):
+ def _parse_kwds(self) -> None:
"""
Validates keywords before passing to pyarrow.
"""
@@ -104,7 +104,7 @@ def _get_pyarrow_options(self) -> None:
] = None # PyArrow raises an exception by default
elif on_bad_lines == ParserBase.BadLineHandleMethod.WARN:
- def handle_warning(invalid_row):
+ def handle_warning(invalid_row) -> str:
warnings.warn(
f"Expected {invalid_row.expected_columns} columns, but found "
f"{invalid_row.actual_columns}: {invalid_row.text}",
@@ -219,7 +219,7 @@ def _finalize_pandas_output(self, frame: DataFrame) -> DataFrame:
raise ValueError(e)
return frame
- def _validate_usecols(self, usecols):
+ def _validate_usecols(self, usecols) -> None:
if lib.is_list_like(usecols) and not all(isinstance(x, str) for x in usecols):
raise ValueError(
"The pyarrow engine does not allow 'usecols' to be integer "
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 50611197ad7dd..1139519d2bcd3 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1707,7 +1707,7 @@ def info(self) -> str:
# ------------------------------------------------------------------------
# private methods
- def _check_if_open(self):
+ def _check_if_open(self) -> None:
if not self.is_open:
raise ClosedFileError(f"{self._path} file is not open!")
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py
index e68f4789f0a06..11b2ed0ee7316 100644
--- a/pandas/io/sas/sas_xport.py
+++ b/pandas/io/sas/sas_xport.py
@@ -288,7 +288,7 @@ def close(self) -> None:
def _get_row(self):
return self.filepath_or_buffer.read(80).decode()
- def _read_header(self):
+ def _read_header(self) -> None:
self.filepath_or_buffer.seek(0)
# read file header
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index b0fa6bc6e90c4..3a58daf681cfb 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1514,7 +1514,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
pass
@@ -2073,7 +2073,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
table = SQLTable(
table_name,
self,
@@ -2433,7 +2433,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
raise NotImplementedError("not implemented for adbc")
@@ -2879,7 +2879,7 @@ def _create_sql_schema(
keys=None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
table = SQLiteTable(
table_name,
self,
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 0f097c6059c7c..a4d8054ea4f8c 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -687,7 +687,7 @@ def __init__(
self._prepare_value_labels()
- def _prepare_value_labels(self):
+ def _prepare_value_labels(self) -> None:
"""Encode value labels."""
self.text_len = 0
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 479a5e19dc1c5..2979903edf360 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -662,7 +662,7 @@ def _ensure_frame(self, data) -> DataFrame:
return data
@final
- def _compute_plot_data(self):
+ def _compute_plot_data(self) -> None:
data = self.data
# GH15079 reconstruct data if by is defined
@@ -699,7 +699,7 @@ def _compute_plot_data(self):
self.data = numeric_data.apply(type(self)._convert_to_ndarray)
- def _make_plot(self, fig: Figure):
+ def _make_plot(self, fig: Figure) -> None:
raise AbstractMethodError(self)
@final
@@ -745,7 +745,7 @@ def _post_plot_logic(self, ax: Axes, data) -> None:
"""Post process for each axes. Overridden in child classes"""
@final
- def _adorn_subplots(self, fig: Figure):
+ def _adorn_subplots(self, fig: Figure) -> None:
"""Common post process unrelated to data"""
if len(self.axes) > 0:
all_axes = self._get_subplots(fig)
@@ -1323,7 +1323,7 @@ def __init__(
c = self.data.columns[c]
self.c = c
- def _make_plot(self, fig: Figure):
+ def _make_plot(self, fig: Figure) -> None:
x, y, c, data = self.x, self.y, self.c, self.data
ax = self.axes[0]
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index a47f622216ef7..cb0b4d549f49e 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -26,7 +26,7 @@
BoolishNoneT = TypeVar("BoolishNoneT", bool, int, None)
-def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
+def _check_arg_length(fname, args, max_fname_arg_count, compat_args) -> None:
"""
Checks whether 'args' has length of at most 'compat_args'. Raises
a TypeError if that is not the case, similar to in Python when a
@@ -46,7 +46,7 @@ def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
)
-def _check_for_default_values(fname, arg_val_dict, compat_args):
+def _check_for_default_values(fname, arg_val_dict, compat_args) -> None:
"""
Check that the keys in `arg_val_dict` are mapped to their
default values as specified in `compat_args`.
@@ -125,7 +125,7 @@ def validate_args(fname, args, max_fname_arg_count, compat_args) -> None:
_check_for_default_values(fname, kwargs, compat_args)
-def _check_for_invalid_keys(fname, kwargs, compat_args):
+def _check_for_invalid_keys(fname, kwargs, compat_args) -> None:
"""
Checks whether 'kwargs' contains any keys that are not
in 'compat_args' and raises a TypeError if there is one.
diff --git a/requirements-dev.txt b/requirements-dev.txt
index cbfb6336b2e16..5a63e59e1db88 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -53,7 +53,7 @@ moto
flask
asv>=0.6.1
flake8==6.1.0
-mypy==1.7.1
+mypy==1.8.0
tokenize-rt
pre-commit>=3.6.0
gitpython
| Backport PR #56617: TYP: some return types from ruff | https://api.github.com/repos/pandas-dev/pandas/pulls/56624 | 2023-12-26T19:38:30Z | 2023-12-26T23:50:48Z | 2023-12-26T23:50:48Z | 2023-12-26T23:50:48Z |
DEPR: Remove array manager branches from tests | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 983272d79081e..046cda259eefd 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1877,14 +1877,6 @@ def indexer_ial(request):
return request.param
-@pytest.fixture
-def using_array_manager() -> bool:
- """
- Fixture to check if the array manager is being used.
- """
- return _get_option("mode.data_manager", silent=True) == "array"
-
-
@pytest.fixture
def using_copy_on_write() -> bool:
"""
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index b7eac6b8f0ea1..0839f005305a5 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -1487,7 +1487,7 @@ def test_apply_dtype(col):
tm.assert_series_equal(result, expected)
-def test_apply_mutating(using_array_manager, using_copy_on_write, warn_copy_on_write):
+def test_apply_mutating(using_copy_on_write, warn_copy_on_write):
# GH#35462 case where applied func pins a new BlockManager to a row
df = DataFrame({"a": range(100), "b": range(100, 200)})
df_orig = df.copy()
@@ -1505,7 +1505,7 @@ def func(row):
result = df.apply(func, axis=1)
tm.assert_frame_equal(result, expected)
- if using_copy_on_write or using_array_manager:
+ if using_copy_on_write:
# INFO(CoW) With copy on write, mutating a viewing row doesn't mutate the parent
# INFO(ArrayManager) With BlockManager, the row is a view and mutated in place,
# with ArrayManager the row is not a view, and thus not mutated in place
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index d8c1786b6b422..ebcd7cbd963d7 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -586,16 +586,12 @@ def test_df_div_zero_series_does_not_commute(self):
# ------------------------------------------------------------------
# Mod By Zero
- def test_df_mod_zero_df(self, using_array_manager):
+ def test_df_mod_zero_df(self):
# GH#3590, modulo as ints
df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
# this is technically wrong, as the integer portion is coerced to float
first = Series([0, 0, 0, 0])
- if not using_array_manager:
- # INFO(ArrayManager) BlockManager doesn't preserve dtype per column
- # while ArrayManager performs op column-wisedoes and thus preserves
- # dtype if possible
- first = first.astype("float64")
+ first = first.astype("float64")
second = Series([np.nan, np.nan, np.nan, 0])
expected = pd.DataFrame({"first": first, "second": second})
result = df % df
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 007d1e670e1e0..b2007209dd5b9 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1736,9 +1736,7 @@ def test_td64_div_object_mixed_result(self, box_with_array):
# ------------------------------------------------------------------
# __floordiv__, __rfloordiv__
- def test_td64arr_floordiv_td64arr_with_nat(
- self, box_with_array, using_array_manager
- ):
+ def test_td64arr_floordiv_td64arr_with_nat(self, box_with_array):
# GH#35529
box = box_with_array
xbox = np.ndarray if box is pd.array else box
@@ -1751,11 +1749,6 @@ def test_td64arr_floordiv_td64arr_with_nat(
expected = np.array([1.0, 1.0, np.nan], dtype=np.float64)
expected = tm.box_expected(expected, xbox)
- if box is DataFrame and using_array_manager:
- # INFO(ArrayManager) floordiv returns integer, and ArrayManager
- # performs ops column-wise and thus preserves int64 dtype for
- # columns without missing values
- expected[[0, 1]] = expected[[0, 1]].astype("int64")
with tm.maybe_produces_warning(
RuntimeWarning, box is pd.array, check_stacklevel=False
diff --git a/pandas/tests/copy_view/test_array.py b/pandas/tests/copy_view/test_array.py
index 9a3f83e0293f5..13f42cce4fe69 100644
--- a/pandas/tests/copy_view/test_array.py
+++ b/pandas/tests/copy_view/test_array.py
@@ -48,7 +48,7 @@ def test_series_values(using_copy_on_write, method):
[lambda df: df.values, lambda df: np.asarray(df)],
ids=["values", "asarray"],
)
-def test_dataframe_values(using_copy_on_write, using_array_manager, method):
+def test_dataframe_values(using_copy_on_write, method):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df_orig = df.copy()
@@ -70,10 +70,7 @@ def test_dataframe_values(using_copy_on_write, using_array_manager, method):
else:
assert arr.flags.writeable is True
arr[0, 0] = 0
- if not using_array_manager:
- assert df.iloc[0, 0] == 0
- else:
- tm.assert_frame_equal(df, df_orig)
+ assert df.iloc[0, 0] == 0
def test_series_to_numpy(using_copy_on_write):
@@ -157,11 +154,10 @@ def test_dataframe_array_ea_dtypes(using_copy_on_write):
assert arr.flags.writeable is True
-def test_dataframe_array_string_dtype(using_copy_on_write, using_array_manager):
+def test_dataframe_array_string_dtype(using_copy_on_write):
df = DataFrame({"a": ["a", "b"]}, dtype="string")
arr = np.asarray(df)
- if not using_array_manager:
- assert np.shares_memory(arr, get_array(df, "a"))
+ assert np.shares_memory(arr, get_array(df, "a"))
if using_copy_on_write:
assert arr.flags.writeable is False
else:
diff --git a/pandas/tests/copy_view/test_constructors.py b/pandas/tests/copy_view/test_constructors.py
index 1aa458a625028..c325e49e8156e 100644
--- a/pandas/tests/copy_view/test_constructors.py
+++ b/pandas/tests/copy_view/test_constructors.py
@@ -339,16 +339,11 @@ def test_dataframe_from_dict_of_series_with_dtype(index):
@pytest.mark.parametrize("copy", [False, None, True])
-def test_frame_from_numpy_array(using_copy_on_write, copy, using_array_manager):
+def test_frame_from_numpy_array(using_copy_on_write, copy):
arr = np.array([[1, 2], [3, 4]])
df = DataFrame(arr, copy=copy)
- if (
- using_copy_on_write
- and copy is not False
- or copy is True
- or (using_array_manager and copy is None)
- ):
+ if using_copy_on_write and copy is not False or copy is True:
assert not np.shares_memory(get_array(df, 0), arr)
else:
assert np.shares_memory(get_array(df, 0), arr)
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py
index 6f3850ab64daa..9afc98e558c11 100644
--- a/pandas/tests/copy_view/test_indexing.py
+++ b/pandas/tests/copy_view/test_indexing.py
@@ -140,15 +140,11 @@ def test_subset_row_slice(backend, using_copy_on_write, warn_copy_on_write):
@pytest.mark.parametrize(
"dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
)
-def test_subset_column_slice(
- backend, using_copy_on_write, warn_copy_on_write, using_array_manager, dtype
-):
+def test_subset_column_slice(backend, using_copy_on_write, warn_copy_on_write, dtype):
# Case: taking a subset of the columns of a DataFrame using a slice
# + afterwards modifying the subset
dtype_backend, DataFrame, _ = backend
- single_block = (
- dtype == "int64" and dtype_backend == "numpy"
- ) and not using_array_manager
+ single_block = dtype == "int64" and dtype_backend == "numpy"
df = DataFrame(
{"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
)
@@ -176,7 +172,7 @@ def test_subset_column_slice(
tm.assert_frame_equal(subset, expected)
# original parent dataframe is not modified (also not for BlockManager case,
# except for single block)
- if not using_copy_on_write and (using_array_manager or single_block):
+ if not using_copy_on_write and single_block:
df_orig.iloc[0, 1] = 0
tm.assert_frame_equal(df, df_orig)
else:
@@ -201,7 +197,6 @@ def test_subset_loc_rows_columns(
dtype,
row_indexer,
column_indexer,
- using_array_manager,
using_copy_on_write,
warn_copy_on_write,
):
@@ -224,14 +219,7 @@ def test_subset_loc_rows_columns(
mutate_parent = (
isinstance(row_indexer, slice)
and isinstance(column_indexer, slice)
- and (
- using_array_manager
- or (
- dtype == "int64"
- and dtype_backend == "numpy"
- and not using_copy_on_write
- )
- )
+ and (dtype == "int64" and dtype_backend == "numpy" and not using_copy_on_write)
)
# modifying the subset never modifies the parent
@@ -265,7 +253,6 @@ def test_subset_iloc_rows_columns(
dtype,
row_indexer,
column_indexer,
- using_array_manager,
using_copy_on_write,
warn_copy_on_write,
):
@@ -288,14 +275,7 @@ def test_subset_iloc_rows_columns(
mutate_parent = (
isinstance(row_indexer, slice)
and isinstance(column_indexer, slice)
- and (
- using_array_manager
- or (
- dtype == "int64"
- and dtype_backend == "numpy"
- and not using_copy_on_write
- )
- )
+ and (dtype == "int64" and dtype_backend == "numpy" and not using_copy_on_write)
)
# modifying the subset never modifies the parent
@@ -422,7 +402,7 @@ def test_subset_set_column(backend, using_copy_on_write, warn_copy_on_write):
"dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
)
def test_subset_set_column_with_loc(
- backend, using_copy_on_write, warn_copy_on_write, using_array_manager, dtype
+ backend, using_copy_on_write, warn_copy_on_write, dtype
):
# Case: setting a single column with loc on a viewing subset
# -> subset.loc[:, col] = value
@@ -440,10 +420,7 @@ def test_subset_set_column_with_loc(
subset.loc[:, "a"] = np.array([10, 11], dtype="int64")
else:
with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(
- None,
- raise_on_extra_warnings=not using_array_manager,
- ):
+ with tm.assert_produces_warning(None):
subset.loc[:, "a"] = np.array([10, 11], dtype="int64")
subset._mgr._verify_integrity()
@@ -461,9 +438,7 @@ def test_subset_set_column_with_loc(
tm.assert_frame_equal(df, df_orig)
-def test_subset_set_column_with_loc2(
- backend, using_copy_on_write, warn_copy_on_write, using_array_manager
-):
+def test_subset_set_column_with_loc2(backend, using_copy_on_write, warn_copy_on_write):
# Case: setting a single column with loc on a viewing subset
# -> subset.loc[:, col] = value
# separate test for case of DataFrame of a single column -> takes a separate
@@ -480,10 +455,7 @@ def test_subset_set_column_with_loc2(
subset.loc[:, "a"] = 0
else:
with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(
- None,
- raise_on_extra_warnings=not using_array_manager,
- ):
+ with tm.assert_produces_warning(None):
subset.loc[:, "a"] = 0
subset._mgr._verify_integrity()
@@ -600,7 +572,6 @@ def test_subset_chained_getitem(
method,
dtype,
using_copy_on_write,
- using_array_manager,
warn_copy_on_write,
):
# Case: creating a subset using multiple, chained getitem calls using views
@@ -614,17 +585,10 @@ def test_subset_chained_getitem(
# when not using CoW, it depends on whether we have a single block or not
# and whether we are slicing the columns -> in that case we have a view
test_callspec = request.node.callspec.id
- if not using_array_manager:
- subset_is_view = test_callspec in (
- "numpy-single-block-column-iloc-slice",
- "numpy-single-block-column-loc-slice",
- )
- else:
- # with ArrayManager, it doesn't matter whether we have
- # single vs mixed block or numpy vs nullable dtypes
- subset_is_view = test_callspec.endswith(
- ("column-iloc-slice", "column-loc-slice")
- )
+ subset_is_view = test_callspec in (
+ "numpy-single-block-column-iloc-slice",
+ "numpy-single-block-column-loc-slice",
+ )
# modify subset -> don't modify parent
subset = method(df)
@@ -726,9 +690,7 @@ def test_subset_chained_getitem_series(
assert subset.iloc[0] == 0
-def test_subset_chained_single_block_row(
- using_copy_on_write, using_array_manager, warn_copy_on_write
-):
+def test_subset_chained_single_block_row(using_copy_on_write, warn_copy_on_write):
# not parametrizing this for dtype backend, since this explicitly tests single block
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
df_orig = df.copy()
@@ -737,7 +699,7 @@ def test_subset_chained_single_block_row(
subset = df[:].iloc[0].iloc[0:2]
with tm.assert_cow_warning(warn_copy_on_write):
subset.iloc[0] = 0
- if using_copy_on_write or using_array_manager:
+ if using_copy_on_write:
tm.assert_frame_equal(df, df_orig)
else:
assert df.iloc[0, 0] == 0
@@ -747,7 +709,7 @@ def test_subset_chained_single_block_row(
with tm.assert_cow_warning(warn_copy_on_write):
df.iloc[0, 0] = 0
expected = Series([1, 4], index=["a", "b"], name=0)
- if using_copy_on_write or using_array_manager:
+ if using_copy_on_write:
tm.assert_series_equal(subset, expected)
else:
assert subset.iloc[0] == 0
@@ -967,9 +929,7 @@ def test_del_series(backend):
# Accessing column as Series
-def test_column_as_series(
- backend, using_copy_on_write, warn_copy_on_write, using_array_manager
-):
+def test_column_as_series(backend, using_copy_on_write, warn_copy_on_write):
# Case: selecting a single column now also uses Copy-on-Write
dtype_backend, DataFrame, Series = backend
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
@@ -979,7 +939,7 @@ def test_column_as_series(
assert np.shares_memory(get_array(s, "a"), get_array(df, "a"))
- if using_copy_on_write or using_array_manager:
+ if using_copy_on_write:
s[0] = 0
else:
if warn_copy_on_write:
@@ -1004,7 +964,7 @@ def test_column_as_series(
def test_column_as_series_set_with_upcast(
- backend, using_copy_on_write, using_array_manager, warn_copy_on_write
+ backend, using_copy_on_write, warn_copy_on_write
):
# Case: selecting a single column now also uses Copy-on-Write -> when
# setting a value causes an upcast, we don't need to update the parent
@@ -1019,7 +979,7 @@ def test_column_as_series_set_with_upcast(
with pytest.raises(TypeError, match="Invalid value"):
s[0] = "foo"
expected = Series([1, 2, 3], name="a")
- elif using_copy_on_write or warn_copy_on_write or using_array_manager:
+ elif using_copy_on_write or warn_copy_on_write:
# TODO(CoW-warn) assert the FutureWarning for CoW is also raised
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
s[0] = "foo"
@@ -1063,7 +1023,6 @@ def test_column_as_series_no_item_cache(
method,
using_copy_on_write,
warn_copy_on_write,
- using_array_manager,
):
# Case: selecting a single column (which now also uses Copy-on-Write to protect
# the view) should always give a new object (i.e. not make use of a cache)
@@ -1080,7 +1039,7 @@ def test_column_as_series_no_item_cache(
else:
assert s1 is s2
- if using_copy_on_write or using_array_manager:
+ if using_copy_on_write:
s1.iloc[0] = 0
elif warn_copy_on_write:
with tm.assert_cow_warning():
@@ -1181,9 +1140,7 @@ def test_series_midx_slice(using_copy_on_write, warn_copy_on_write):
tm.assert_series_equal(ser, expected)
-def test_getitem_midx_slice(
- using_copy_on_write, warn_copy_on_write, using_array_manager
-):
+def test_getitem_midx_slice(using_copy_on_write, warn_copy_on_write):
df = DataFrame({("a", "x"): [1, 2], ("a", "y"): 1, ("b", "x"): 2})
df_orig = df.copy()
new_df = df[("a",)]
@@ -1191,8 +1148,7 @@ def test_getitem_midx_slice(
if using_copy_on_write:
assert not new_df._mgr._has_no_reference(0)
- if not using_array_manager:
- assert np.shares_memory(get_array(df, ("a", "x")), get_array(new_df, "x"))
+ assert np.shares_memory(get_array(df, ("a", "x")), get_array(new_df, "x"))
if using_copy_on_write:
new_df.iloc[0, 0] = 100
tm.assert_frame_equal(df_orig, df)
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 862aebdc70a9d..590829b6dc759 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -119,9 +119,7 @@ def test_copy_shallow(using_copy_on_write, warn_copy_on_write):
"set_flags",
],
)
-def test_methods_copy_keyword(
- request, method, copy, using_copy_on_write, using_array_manager
-):
+def test_methods_copy_keyword(request, method, copy, using_copy_on_write):
index = None
if "to_timestamp" in request.node.callspec.id:
index = period_range("2012-01-01", freq="D", periods=3)
@@ -145,7 +143,7 @@ def test_methods_copy_keyword(
if request.node.callspec.id.startswith("reindex-"):
# TODO copy=False without CoW still returns a copy in this case
- if not using_copy_on_write and not using_array_manager and copy is False:
+ if not using_copy_on_write and copy is False:
share_memory = False
if share_memory:
@@ -227,11 +225,10 @@ def test_methods_series_copy_keyword(request, method, copy, using_copy_on_write)
@pytest.mark.parametrize("copy", [True, None, False])
-def test_transpose_copy_keyword(using_copy_on_write, copy, using_array_manager):
+def test_transpose_copy_keyword(using_copy_on_write, copy):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
result = df.transpose(copy=copy)
share_memory = using_copy_on_write or copy is False or copy is None
- share_memory = share_memory and not using_array_manager
if share_memory:
assert np.shares_memory(get_array(df, "a"), get_array(result, 0))
@@ -1718,11 +1715,8 @@ def test_get(using_copy_on_write, warn_copy_on_write, key):
@pytest.mark.parametrize(
"dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
)
-def test_xs(
- using_copy_on_write, warn_copy_on_write, using_array_manager, axis, key, dtype
-):
- single_block = (dtype == "int64") and not using_array_manager
- is_view = single_block or (using_array_manager and axis == 1)
+def test_xs(using_copy_on_write, warn_copy_on_write, axis, key, dtype):
+ single_block = dtype == "int64"
df = DataFrame(
{"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
)
@@ -1735,7 +1729,7 @@ def test_xs(
elif using_copy_on_write:
assert result._mgr._has_no_reference(0)
- if using_copy_on_write or (is_view and not warn_copy_on_write):
+ if using_copy_on_write or (single_block and not warn_copy_on_write):
result.iloc[0] = 0
elif warn_copy_on_write:
with tm.assert_cow_warning(single_block or axis == 1):
@@ -1753,9 +1747,7 @@ def test_xs(
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("key, level", [("l1", 0), (2, 1)])
-def test_xs_multiindex(
- using_copy_on_write, warn_copy_on_write, using_array_manager, key, level, axis
-):
+def test_xs_multiindex(using_copy_on_write, warn_copy_on_write, key, level, axis):
arr = np.arange(18).reshape(6, 3)
index = MultiIndex.from_product([["l1", "l2"], [1, 2, 3]], names=["lev1", "lev2"])
df = DataFrame(arr, index=index, columns=list("abc"))
@@ -1772,7 +1764,7 @@ def test_xs_multiindex(
if warn_copy_on_write:
warn = FutureWarning if level == 0 else None
- elif not using_copy_on_write and not using_array_manager:
+ elif not using_copy_on_write:
warn = SettingWithCopyWarning
else:
warn = None
@@ -1884,12 +1876,12 @@ def test_inplace_arithmetic_series_with_reference(
@pytest.mark.parametrize("copy", [True, False])
-def test_transpose(using_copy_on_write, copy, using_array_manager):
+def test_transpose(using_copy_on_write, copy):
df = DataFrame({"a": [1, 2, 3], "b": 1})
df_orig = df.copy()
result = df.transpose(copy=copy)
- if not copy and not using_array_manager or using_copy_on_write:
+ if not copy or using_copy_on_write:
assert np.shares_memory(get_array(df, "a"), get_array(result, 0))
else:
assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py
index 6d16bc3083883..1a0a77b332743 100644
--- a/pandas/tests/copy_view/test_replace.py
+++ b/pandas/tests/copy_view/test_replace.py
@@ -118,7 +118,7 @@ def test_replace_mask_all_false_second_block(using_copy_on_write):
# assert np.shares_memory(get_array(df, "d"), get_array(df2, "d"))
-def test_replace_coerce_single_column(using_copy_on_write, using_array_manager):
+def test_replace_coerce_single_column(using_copy_on_write):
df = DataFrame({"a": [1.5, 2, 3], "b": 100.5})
df_orig = df.copy()
@@ -128,7 +128,7 @@ def test_replace_coerce_single_column(using_copy_on_write, using_array_manager):
assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
- elif not using_array_manager:
+ else:
assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py
index ca19845041e23..9dd0a2eba6c0d 100644
--- a/pandas/tests/extension/base/setitem.py
+++ b/pandas/tests/extension/base/setitem.py
@@ -397,10 +397,6 @@ def test_setitem_series(self, data, full_indexer):
def test_setitem_frame_2d_values(self, data):
# GH#44514
df = pd.DataFrame({"A": data})
-
- # Avoiding using_array_manager fixture
- # https://github.com/pandas-dev/pandas/pull/44514#discussion_r754002410
- using_array_manager = isinstance(df._mgr, pd.core.internals.ArrayManager)
using_copy_on_write = pd.options.mode.copy_on_write
blk_data = df._mgr.arrays[0]
@@ -415,7 +411,7 @@ def test_setitem_frame_2d_values(self, data):
df.iloc[:] = df.values
tm.assert_frame_equal(df, orig)
- if not using_array_manager and not using_copy_on_write:
+ if not using_copy_on_write:
# GH#33457 Check that this setting occurred in-place
# FIXME(ArrayManager): this should work there too
assert df._mgr.arrays[0] is blk_data
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 97e7ae15c6c63..7837adec0c9e0 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -739,7 +739,7 @@ def test_getitem_setitem_boolean_multi(self):
expected.loc[[0, 2], [1]] = 5
tm.assert_frame_equal(df, expected)
- def test_getitem_setitem_float_labels(self, using_array_manager):
+ def test_getitem_setitem_float_labels(self):
index = Index([1.5, 2, 3, 4, 5])
df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)), index=index)
@@ -1110,16 +1110,14 @@ def test_iloc_col(self):
expected = df.reindex(columns=df.columns[[1, 2, 4, 6]])
tm.assert_frame_equal(result, expected)
- def test_iloc_col_slice_view(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
- ):
+ def test_iloc_col_slice_view(self, using_copy_on_write, warn_copy_on_write):
df = DataFrame(
np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2)
)
original = df.copy()
subset = df.iloc[:, slice(4, 8)]
- if not using_array_manager and not using_copy_on_write:
+ if not using_copy_on_write:
# verify slice is view
assert np.shares_memory(df[8]._values, subset[8]._values)
@@ -1617,7 +1615,7 @@ def test_setitem(self):
)
-def test_object_casting_indexing_wraps_datetimelike(using_array_manager):
+def test_object_casting_indexing_wraps_datetimelike():
# GH#31649, check the indexing methods all the way down the stack
df = DataFrame(
{
@@ -1639,10 +1637,6 @@ def test_object_casting_indexing_wraps_datetimelike(using_array_manager):
assert isinstance(ser.values[1], Timestamp)
assert isinstance(ser.values[2], pd.Timedelta)
- if using_array_manager:
- # remainder of the test checking BlockManager internals
- return
-
mgr = df._mgr
mgr._rebuild_blknos_and_blklocs()
arr = mgr.fast_xs(0).array
diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py
index 7e702bdc993bd..b9fc5dc195026 100644
--- a/pandas/tests/frame/indexing/test_insert.py
+++ b/pandas/tests/frame/indexing/test_insert.py
@@ -71,15 +71,10 @@ def test_insert_with_columns_dups(self):
)
tm.assert_frame_equal(df, exp)
- def test_insert_item_cache(self, using_array_manager, using_copy_on_write):
+ def test_insert_item_cache(self, using_copy_on_write):
df = DataFrame(np.random.default_rng(2).standard_normal((4, 3)))
ser = df[0]
-
- if using_array_manager:
- expected_warning = None
- else:
- # with BlockManager warn about high fragmentation of single dtype
- expected_warning = PerformanceWarning
+ expected_warning = PerformanceWarning
with tm.assert_produces_warning(expected_warning):
for n in range(100):
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index e802a56ecbc81..f031cb2218e31 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -1208,9 +1208,7 @@ def test_setitem_always_copy(self, float_frame):
assert notna(s[5:10]).all()
@pytest.mark.parametrize("consolidate", [True, False])
- def test_setitem_partial_column_inplace(
- self, consolidate, using_array_manager, using_copy_on_write
- ):
+ def test_setitem_partial_column_inplace(self, consolidate, using_copy_on_write):
# This setting should be in-place, regardless of whether frame is
# single-block or multi-block
# GH#304 this used to be incorrectly not-inplace, in which case
@@ -1220,12 +1218,11 @@ def test_setitem_partial_column_inplace(
{"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3]
)
df.insert(2, "z", np.nan)
- if not using_array_manager:
- if consolidate:
- df._consolidate_inplace()
- assert len(df._mgr.blocks) == 1
- else:
- assert len(df._mgr.blocks) == 2
+ if consolidate:
+ df._consolidate_inplace()
+ assert len(df._mgr.blocks) == 1
+ else:
+ assert len(df._mgr.blocks) == 2
zvals = df["z"]._values
@@ -1254,7 +1251,7 @@ def test_setitem_duplicate_columns_not_inplace(self):
@pytest.mark.parametrize(
"value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]]
)
- def test_setitem_same_dtype_not_inplace(self, value, using_array_manager):
+ def test_setitem_same_dtype_not_inplace(self, value):
# GH#39510
cols = ["A", "B"]
df = DataFrame(0, index=[0, 1], columns=cols)
diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py
index be809e3a17c8e..535137edd16cf 100644
--- a/pandas/tests/frame/indexing/test_xs.py
+++ b/pandas/tests/frame/indexing/test_xs.py
@@ -122,9 +122,7 @@ def test_xs_keep_level(self):
result = df.xs((2008, "sat"), level=["year", "day"], drop_level=False)
tm.assert_frame_equal(result, expected)
- def test_xs_view(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
- ):
+ def test_xs_view(self, using_copy_on_write, warn_copy_on_write):
# in 0.14 this will return a view if possible a copy otherwise, but
# this is numpy dependent
@@ -135,13 +133,6 @@ def test_xs_view(
with tm.raises_chained_assignment_error():
dm.xs(2)[:] = 20
tm.assert_frame_equal(dm, df_orig)
- elif using_array_manager:
- # INFO(ArrayManager) with ArrayManager getting a row as a view is
- # not possible
- msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- dm.xs(2)[:] = 20
- assert not (dm.xs(2) == 20).any()
else:
with tm.raises_chained_assignment_error():
dm.xs(2)[:] = 20
@@ -400,9 +391,7 @@ def test_xs_droplevel_false(self):
expected = DataFrame({"a": [1]})
tm.assert_frame_equal(result, expected)
- def test_xs_droplevel_false_view(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
- ):
+ def test_xs_droplevel_false_view(self, using_copy_on_write, warn_copy_on_write):
# GH#37832
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
result = df.xs("a", axis=1, drop_level=False)
@@ -427,9 +416,6 @@ def test_xs_droplevel_false_view(
if using_copy_on_write:
# with copy on write the subset is never modified
expected = DataFrame({"a": [1]})
- elif using_array_manager:
- # Here the behavior is consistent
- expected = DataFrame({"a": [2]})
else:
# FIXME: iloc does not update the array inplace using
# "split" path
diff --git a/pandas/tests/frame/methods/test_equals.py b/pandas/tests/frame/methods/test_equals.py
index d0b9d96cafa0d..88b3fec02182b 100644
--- a/pandas/tests/frame/methods/test_equals.py
+++ b/pandas/tests/frame/methods/test_equals.py
@@ -14,11 +14,11 @@ def test_dataframe_not_equal(self):
df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})
assert df1.equals(df2) is False
- def test_equals_different_blocks(self, using_array_manager, using_infer_string):
+ def test_equals_different_blocks(self, using_infer_string):
# GH#9330
df0 = DataFrame({"A": ["x", "y"], "B": [1, 2], "C": ["w", "z"]})
df1 = df0.reset_index()[["A", "B", "C"]]
- if not using_array_manager and not using_infer_string:
+ if not using_infer_string:
# this assert verifies that the above operations have
# induced a block rearrangement
assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index e0641fcb65bd3..a93931a970687 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -52,12 +52,8 @@ def test_interpolate_datetimelike_values(self, frame_or_series):
expected_td = frame_or_series(orig - orig[0])
tm.assert_equal(res_td, expected_td)
- def test_interpolate_inplace(self, frame_or_series, using_array_manager, request):
+ def test_interpolate_inplace(self, frame_or_series, request):
# GH#44749
- if using_array_manager and frame_or_series is DataFrame:
- mark = pytest.mark.xfail(reason=".values-based in-place check is invalid")
- request.applymarker(mark)
-
obj = frame_or_series([1, np.nan, 2])
orig = obj.values
@@ -474,14 +470,8 @@ def test_interp_string_axis(self, axis_name, axis_number):
@pytest.mark.parametrize("multiblock", [True, False])
@pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])
- def test_interp_fillna_methods(
- self, request, axis, multiblock, method, using_array_manager
- ):
+ def test_interp_fillna_methods(self, request, axis, multiblock, method):
# GH 12918
- if using_array_manager and axis in (1, "columns"):
- # TODO(ArrayManager) support axis=1
- td.mark_array_manager_not_yet_implemented(request)
-
df = DataFrame(
{
"A": [1.0, 2.0, 3.0, 4.0, np.nan, 5.0],
diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py
index 0f27eae1a3bfc..e31e29b1b0cb2 100644
--- a/pandas/tests/frame/methods/test_quantile.py
+++ b/pandas/tests/frame/methods/test_quantile.py
@@ -45,9 +45,7 @@ def test_quantile_sparse(self, df, expected):
expected = expected.astype("Sparse[float]")
tm.assert_series_equal(result, expected)
- def test_quantile(
- self, datetime_frame, interp_method, using_array_manager, request
- ):
+ def test_quantile(self, datetime_frame, interp_method, request):
interpolation, method = interp_method
df = datetime_frame
result = df.quantile(
@@ -63,11 +61,6 @@ def test_quantile(
tm.assert_series_equal(result, expected)
else:
tm.assert_index_equal(result.index, expected.index)
- request.applymarker(
- pytest.mark.xfail(
- using_array_manager, reason="Name set incorrectly for arraymanager"
- )
- )
assert result.name == expected.name
result = df.quantile(
@@ -83,11 +76,6 @@ def test_quantile(
tm.assert_series_equal(result, expected)
else:
tm.assert_index_equal(result.index, expected.index)
- request.applymarker(
- pytest.mark.xfail(
- using_array_manager, reason="Name set incorrectly for arraymanager"
- )
- )
assert result.name == expected.name
def test_empty(self, interp_method):
@@ -97,7 +85,7 @@ def test_empty(self, interp_method):
)
assert np.isnan(q["x"]) and np.isnan(q["y"])
- def test_non_numeric_exclusion(self, interp_method, request, using_array_manager):
+ def test_non_numeric_exclusion(self, interp_method, request):
interpolation, method = interp_method
df = DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]})
rs = df.quantile(
@@ -106,11 +94,9 @@ def test_non_numeric_exclusion(self, interp_method, request, using_array_manager
xp = df.median(numeric_only=True).rename(0.5)
if interpolation == "nearest":
xp = (xp + 0.5).astype(np.int64)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_series_equal(rs, xp)
- def test_axis(self, interp_method, request, using_array_manager):
+ def test_axis(self, interp_method):
# axis
interpolation, method = interp_method
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
@@ -118,8 +104,6 @@ def test_axis(self, interp_method, request, using_array_manager):
expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5)
if interpolation == "nearest":
expected = expected.astype(np.int64)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_series_equal(result, expected)
result = df.quantile(
@@ -134,7 +118,7 @@ def test_axis(self, interp_method, request, using_array_manager):
expected = expected.astype(np.int64)
tm.assert_frame_equal(result, expected, check_index_type=True)
- def test_axis_numeric_only_true(self, interp_method, request, using_array_manager):
+ def test_axis_numeric_only_true(self, interp_method):
# We may want to break API in the future to change this
# so that we exclude non-numeric along the same axis
# See GH #7312
@@ -146,11 +130,9 @@ def test_axis_numeric_only_true(self, interp_method, request, using_array_manage
expected = Series([3.0, 4.0], index=[0, 1], name=0.5)
if interpolation == "nearest":
expected = expected.astype(np.int64)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_series_equal(result, expected)
- def test_quantile_date_range(self, interp_method, request, using_array_manager):
+ def test_quantile_date_range(self, interp_method):
# GH 2460
interpolation, method = interp_method
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
@@ -163,12 +145,10 @@ def test_quantile_date_range(self, interp_method, request, using_array_manager):
expected = Series(
["2016-01-02 00:00:00"], name=0.5, dtype="datetime64[ns, US/Pacific]"
)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_series_equal(result, expected)
- def test_quantile_axis_mixed(self, interp_method, request, using_array_manager):
+ def test_quantile_axis_mixed(self, interp_method):
# mixed on axis=1
interpolation, method = interp_method
df = DataFrame(
@@ -185,8 +165,6 @@ def test_quantile_axis_mixed(self, interp_method, request, using_array_manager):
expected = Series([1.5, 2.5, 3.5], name=0.5)
if interpolation == "nearest":
expected -= 0.5
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_series_equal(result, expected)
# must raise
@@ -194,11 +172,9 @@ def test_quantile_axis_mixed(self, interp_method, request, using_array_manager):
with pytest.raises(TypeError, match=msg):
df.quantile(0.5, axis=1, numeric_only=False)
- def test_quantile_axis_parameter(self, interp_method, request, using_array_manager):
+ def test_quantile_axis_parameter(self, interp_method):
# GH 9543/9544
interpolation, method = interp_method
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
result = df.quantile(0.5, axis=0, interpolation=interpolation, method=method)
@@ -312,7 +288,7 @@ def test_quantile_interpolation_int(self, int_frame):
assert q1["A"] == np.percentile(df["A"], 10)
tm.assert_series_equal(q, q1)
- def test_quantile_multi(self, interp_method, request, using_array_manager):
+ def test_quantile_multi(self, interp_method):
interpolation, method = interp_method
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])
result = df.quantile([0.25, 0.5], interpolation=interpolation, method=method)
@@ -323,11 +299,9 @@ def test_quantile_multi(self, interp_method, request, using_array_manager):
)
if interpolation == "nearest":
expected = expected.astype(np.int64)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_frame_equal(result, expected)
- def test_quantile_multi_axis_1(self, interp_method, request, using_array_manager):
+ def test_quantile_multi_axis_1(self, interp_method):
interpolation, method = interp_method
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])
result = df.quantile(
@@ -338,8 +312,6 @@ def test_quantile_multi_axis_1(self, interp_method, request, using_array_manager
)
if interpolation == "nearest":
expected = expected.astype(np.int64)
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
tm.assert_frame_equal(result, expected)
def test_quantile_multi_empty(self, interp_method):
@@ -443,10 +415,8 @@ def test_quantile_invalid(self, invalid, datetime_frame, interp_method):
with pytest.raises(ValueError, match=msg):
datetime_frame.quantile(invalid, interpolation=interpolation, method=method)
- def test_quantile_box(self, interp_method, request, using_array_manager):
+ def test_quantile_box(self, interp_method):
interpolation, method = interp_method
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
df = DataFrame(
{
"A": [
@@ -574,10 +544,8 @@ def test_quantile_box_nat(self):
)
tm.assert_frame_equal(res, exp)
- def test_quantile_nan(self, interp_method, request, using_array_manager):
+ def test_quantile_nan(self, interp_method):
interpolation, method = interp_method
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
# GH 14357 - float block where some cols have missing values
df = DataFrame({"a": np.arange(1, 6.0), "b": np.arange(1, 6.0)})
df.iloc[-1, 1] = np.nan
@@ -621,10 +589,8 @@ def test_quantile_nan(self, interp_method, request, using_array_manager):
exp = DataFrame({"a": [3.0, 4.0], "b": [np.nan, np.nan]}, index=[0.5, 0.75])
tm.assert_frame_equal(res, exp)
- def test_quantile_nat(self, interp_method, request, using_array_manager, unit):
+ def test_quantile_nat(self, interp_method, unit):
interpolation, method = interp_method
- if method == "table" and using_array_manager:
- request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
# full NaT column
df = DataFrame({"a": [pd.NaT, pd.NaT, pd.NaT]}, dtype=f"M8[{unit}]")
@@ -757,9 +723,7 @@ def test_quantile_empty_no_columns(self, interp_method):
expected.columns.name = "captain tightpants"
tm.assert_frame_equal(result, expected)
- def test_quantile_item_cache(
- self, using_array_manager, interp_method, using_copy_on_write
- ):
+ def test_quantile_item_cache(self, interp_method, using_copy_on_write):
# previous behavior incorrect retained an invalid _item_cache entry
interpolation, method = interp_method
df = DataFrame(
@@ -767,8 +731,7 @@ def test_quantile_item_cache(
)
df["D"] = df["A"] * 2
ser = df["A"]
- if not using_array_manager:
- assert len(df._mgr.blocks) == 2
+ assert len(df._mgr.blocks) == 2
df.quantile(numeric_only=False, interpolation=interpolation, method=method)
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index b21aa2d687682..907ff67eac7a1 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -423,13 +423,12 @@ def test_shift_duplicate_columns(self):
tm.assert_frame_equal(shifted[0], shifted[1])
tm.assert_frame_equal(shifted[0], shifted[2])
- def test_shift_axis1_multiple_blocks(self, using_array_manager):
+ def test_shift_axis1_multiple_blocks(self):
# GH#35488
df1 = DataFrame(np.random.default_rng(2).integers(1000, size=(5, 3)))
df2 = DataFrame(np.random.default_rng(2).integers(1000, size=(5, 2)))
df3 = pd.concat([df1, df2], axis=1)
- if not using_array_manager:
- assert len(df3._mgr.blocks) == 2
+ assert len(df3._mgr.blocks) == 2
result = df3.shift(2, axis=1)
@@ -449,8 +448,7 @@ def test_shift_axis1_multiple_blocks(self, using_array_manager):
# Case with periods < 0
# rebuild df3 because `take` call above consolidated
df3 = pd.concat([df1, df2], axis=1)
- if not using_array_manager:
- assert len(df3._mgr.blocks) == 2
+ assert len(df3._mgr.blocks) == 2
result = df3.shift(-2, axis=1)
expected = df3.take([2, 3, 4, -1, -1], axis=1)
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index f2f02058a534e..be75efcdfe9d3 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -598,15 +598,14 @@ def test_sort_values_nat_na_position_default(self):
result = expected.sort_values(["A", "date"])
tm.assert_frame_equal(result, expected)
- def test_sort_values_item_cache(self, using_array_manager, using_copy_on_write):
+ def test_sort_values_item_cache(self, using_copy_on_write):
# previous behavior incorrect retained an invalid _item_cache entry
df = DataFrame(
np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"]
)
df["D"] = df["A"] * 2
ser = df["A"]
- if not using_array_manager:
- assert len(df._mgr.blocks) == 2
+ assert len(df._mgr.blocks) == 2
df.sort_values(by="A")
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index 42ce658701355..ecaf826c46d9b 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -13,8 +13,6 @@
from pandas._config import using_pyarrow_string_dtype
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
DataFrame,
@@ -894,15 +892,11 @@ def test_df_add_2d_array_collike_broadcasts(self):
tm.assert_frame_equal(result, expected)
def test_df_arith_2d_array_rowlike_broadcasts(
- self, request, all_arithmetic_operators, using_array_manager
+ self, request, all_arithmetic_operators
):
# GH#23000
opname = all_arithmetic_operators
- if using_array_manager and opname in ("__rmod__", "__rfloordiv__"):
- # TODO(ArrayManager) decide on dtypes
- td.mark_array_manager_not_yet_implemented(request)
-
arr = np.arange(6).reshape(3, 2)
df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
@@ -921,15 +915,11 @@ def test_df_arith_2d_array_rowlike_broadcasts(
tm.assert_frame_equal(result, expected)
def test_df_arith_2d_array_collike_broadcasts(
- self, request, all_arithmetic_operators, using_array_manager
+ self, request, all_arithmetic_operators
):
# GH#23000
opname = all_arithmetic_operators
- if using_array_manager and opname in ("__rmod__", "__rfloordiv__"):
- # TODO(ArrayManager) decide on dtypes
- td.mark_array_manager_not_yet_implemented(request)
-
arr = np.arange(6).reshape(3, 2)
df = DataFrame(arr, columns=[True, False], index=["A", "B", "C"])
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 6e818d79d5ba8..8ff69472ea113 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -84,16 +84,15 @@ def test_constructor_from_ndarray_with_str_dtype(self):
expected = DataFrame(arr.astype(str), dtype=object)
tm.assert_frame_equal(df, expected)
- def test_constructor_from_2d_datetimearray(self, using_array_manager):
+ def test_constructor_from_2d_datetimearray(self):
dti = date_range("2016-01-01", periods=6, tz="US/Pacific")
dta = dti._data.reshape(3, 2)
df = DataFrame(dta)
expected = DataFrame({0: dta[:, 0], 1: dta[:, 1]})
tm.assert_frame_equal(df, expected)
- if not using_array_manager:
- # GH#44724 big performance hit if we de-consolidate
- assert len(df._mgr.blocks) == 1
+ # GH#44724 big performance hit if we de-consolidate
+ assert len(df._mgr.blocks) == 1
def test_constructor_dict_with_tzaware_scalar(self):
# GH#42505
@@ -310,10 +309,10 @@ def test_constructor_dtype_nocast_view_dataframe(
assert df.values[0, 0] == 99
def test_constructor_dtype_nocast_view_2d_array(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
+ self, using_copy_on_write, warn_copy_on_write
):
df = DataFrame([[1, 2], [3, 4]], dtype="int64")
- if not using_array_manager and not using_copy_on_write:
+ if not using_copy_on_write:
should_be_view = DataFrame(df.values, dtype=df[0].dtype)
# TODO(CoW-warn) this should warn
# with tm.assert_cow_warning(warn_copy_on_write):
@@ -2147,35 +2146,19 @@ def test_constructor_frame_shallow_copy(self, float_frame):
cop.index = np.arange(len(cop))
tm.assert_frame_equal(float_frame, orig)
- def test_constructor_ndarray_copy(
- self, float_frame, using_array_manager, using_copy_on_write
- ):
- if not using_array_manager:
- arr = float_frame.values.copy()
- df = DataFrame(arr)
-
- arr[5] = 5
- if using_copy_on_write:
- assert not (df.values[5] == 5).all()
- else:
- assert (df.values[5] == 5).all()
+ def test_constructor_ndarray_copy(self, float_frame, using_copy_on_write):
+ arr = float_frame.values.copy()
+ df = DataFrame(arr)
- df = DataFrame(arr, copy=True)
- arr[6] = 6
- assert not (df.values[6] == 6).all()
+ arr[5] = 5
+ if using_copy_on_write:
+ assert not (df.values[5] == 5).all()
else:
- arr = float_frame.values.copy()
- # default: copy to ensure contiguous arrays
- df = DataFrame(arr)
- assert df._mgr.arrays[0].flags.c_contiguous
- arr[0, 0] = 100
- assert df.iloc[0, 0] != 100
-
- # manually specify copy=False
- df = DataFrame(arr, copy=False)
- assert not df._mgr.arrays[0].flags.c_contiguous
- arr[0, 0] = 1000
- assert df.iloc[0, 0] == 1000
+ assert (df.values[5] == 5).all()
+
+ df = DataFrame(arr, copy=True)
+ arr[6] = 6
+ assert not (df.values[6] == 6).all()
def test_constructor_series_copy(self, float_frame):
series = float_frame._series
@@ -2328,15 +2311,10 @@ def test_check_dtype_empty_numeric_column(self, dtype):
@pytest.mark.parametrize(
"dtype", tm.STRING_DTYPES + tm.BYTES_DTYPES + tm.OBJECT_DTYPES
)
- def test_check_dtype_empty_string_column(self, request, dtype, using_array_manager):
+ def test_check_dtype_empty_string_column(self, request, dtype):
# GH24386: Ensure dtypes are set correctly for an empty DataFrame.
# Empty DataFrame is generated via dictionary data with non-overlapping columns.
data = DataFrame({"a": [1, 2]}, columns=["b"], dtype=dtype)
-
- if using_array_manager and dtype in tm.BYTES_DTYPES:
- # TODO(ArrayManager) astype to bytes dtypes does not yet give object dtype
- td.mark_array_manager_not_yet_implemented(request)
-
assert data.b.dtype.name == "object"
def test_to_frame_with_falsey_names(self):
@@ -2515,17 +2493,8 @@ def test_dict_nocopy(
copy,
any_numeric_ea_dtype,
any_numpy_dtype,
- using_array_manager,
using_copy_on_write,
):
- if (
- using_array_manager
- and not copy
- and any_numpy_dtype not in tm.STRING_DTYPES + tm.BYTES_DTYPES
- ):
- # TODO(ArrayManager) properly honor copy keyword for dict input
- td.mark_array_manager_not_yet_implemented(request)
-
a = np.array([1, 2], dtype=any_numpy_dtype)
b = np.array([3, 4], dtype=any_numpy_dtype)
if b.dtype.kind in ["S", "U"]:
diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py
index 34f172e900ab7..1e9aa2325e880 100644
--- a/pandas/tests/frame/test_nonunique_indexes.py
+++ b/pandas/tests/frame/test_nonunique_indexes.py
@@ -284,7 +284,7 @@ def test_multi_dtype2(self):
expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"])
tm.assert_frame_equal(df, expected)
- def test_dups_across_blocks(self, using_array_manager):
+ def test_dups_across_blocks(self):
# dups across blocks
df_float = DataFrame(
np.random.default_rng(2).standard_normal((10, 3)), dtype="float64"
@@ -299,9 +299,8 @@ def test_dups_across_blocks(self, using_array_manager):
)
df = pd.concat([df_float, df_int, df_bool, df_object, df_dt], axis=1)
- if not using_array_manager:
- assert len(df._mgr.blknos) == len(df.columns)
- assert len(df._mgr.blklocs) == len(df.columns)
+ assert len(df._mgr.blknos) == len(df.columns)
+ assert len(df._mgr.blklocs) == len(df.columns)
# testing iloc
for i in range(len(df.columns)):
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 66145c32c18d7..512b5d6ace469 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -817,17 +817,8 @@ def test_std_timedelta64_skipna_false(self):
@pytest.mark.parametrize(
"values", [["2022-01-01", "2022-01-02", pd.NaT, "2022-01-03"], 4 * [pd.NaT]]
)
- def test_std_datetime64_with_nat(
- self, values, skipna, using_array_manager, request, unit
- ):
+ def test_std_datetime64_with_nat(self, values, skipna, request, unit):
# GH#51335
- if using_array_manager and (
- not skipna or all(value is pd.NaT for value in values)
- ):
- mark = pytest.mark.xfail(
- reason="GH#51446: Incorrect type inference on NaT in reduction result"
- )
- request.applymarker(mark)
dti = to_datetime(values).as_unit(unit)
df = DataFrame({"a": dti})
result = df.std(skipna=skipna)
@@ -1926,14 +1917,8 @@ def test_df_empty_nullable_min_count_1(self, opname, dtype, exp_dtype):
tm.assert_series_equal(result, expected)
-def test_sum_timedelta64_skipna_false(using_array_manager, request):
+def test_sum_timedelta64_skipna_false():
# GH#17235
- if using_array_manager:
- mark = pytest.mark.xfail(
- reason="Incorrect type inference on NaT in reduction result"
- )
- request.applymarker(mark)
-
arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2)
arr[-1, -1] = "Nat"
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 6e1e743eb60de..ea66290ab0417 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -72,13 +72,12 @@ def test_stack_mixed_level(self, future_stack):
expected = expected[["a", "b"]]
tm.assert_frame_equal(result, expected)
- def test_unstack_not_consolidated(self, using_array_manager):
+ def test_unstack_not_consolidated(self):
# Gh#34708
df = DataFrame({"x": [1, 2, np.nan], "y": [3.0, 4, np.nan]})
df2 = df[["x"]]
df2["y"] = df["y"]
- if not using_array_manager:
- assert len(df2._mgr.blocks) == 2
+ assert len(df2._mgr.blocks) == 2
res = df2.unstack()
expected = df.unstack()
@@ -969,7 +968,7 @@ def test_unstack_nan_index2(self):
right = DataFrame(vals, columns=cols, index=idx)
tm.assert_frame_equal(left, right)
- def test_unstack_nan_index3(self, using_array_manager):
+ def test_unstack_nan_index3(self):
# GH7401
df = DataFrame(
{
@@ -991,10 +990,6 @@ def test_unstack_nan_index3(self, using_array_manager):
)
right = DataFrame(vals, columns=cols, index=idx)
- if using_array_manager:
- # INFO(ArrayManager) with ArrayManager preserve dtype where possible
- cols = right.columns[[1, 2, 3, 5]]
- right[cols] = right[cols].astype(df["C"].dtype)
tm.assert_frame_equal(left, right)
def test_unstack_nan_index4(self):
@@ -1498,7 +1493,7 @@ def test_stack_positional_level_duplicate_column_names(future_stack):
tm.assert_frame_equal(result, expected)
-def test_unstack_non_slice_like_blocks(using_array_manager):
+def test_unstack_non_slice_like_blocks():
# Case where the mgr_locs of a DataFrame's underlying blocks are not slice-like
mi = MultiIndex.from_product([range(5), ["A", "B", "C"]])
@@ -1511,8 +1506,7 @@ def test_unstack_non_slice_like_blocks(using_array_manager):
},
index=mi,
)
- if not using_array_manager:
- assert any(not x.mgr_locs.is_slice_like for x in df._mgr.blocks)
+ assert any(not x.mgr_locs.is_slice_like for x in df._mgr.blocks)
res = df.unstack()
@@ -2354,7 +2348,7 @@ def test_unstack_group_index_overflow(self, future_stack):
result = s.unstack(4)
assert result.shape == (500, 2)
- def test_unstack_with_missing_int_cast_to_float(self, using_array_manager):
+ def test_unstack_with_missing_int_cast_to_float(self):
# https://github.com/pandas-dev/pandas/issues/37115
df = DataFrame(
{
@@ -2366,8 +2360,7 @@ def test_unstack_with_missing_int_cast_to_float(self, using_array_manager):
# add another int column to get 2 blocks
df["is_"] = 1
- if not using_array_manager:
- assert len(df._mgr.blocks) == 2
+ assert len(df._mgr.blocks) == 2
result = df.unstack("b")
result[("is_", "ca")] = result[("is_", "ca")].fillna(0)
@@ -2380,10 +2373,6 @@ def test_unstack_with_missing_int_cast_to_float(self, using_array_manager):
names=[None, "b"],
),
)
- if using_array_manager:
- # INFO(ArrayManager) with ArrayManager preserve dtype where possible
- expected[("v", "cb")] = expected[("v", "cb")].astype("int64")
- expected[("is_", "cb")] = expected[("is_", "cb")].astype("int64")
tm.assert_frame_equal(result, expected)
def test_unstack_with_level_has_nan(self):
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 4c903e691add1..3cc06ae4d2387 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2050,9 +2050,7 @@ def test_pivot_table_values_key_error():
@pytest.mark.parametrize(
"op", ["idxmax", "idxmin", "min", "max", "sum", "prod", "skew"]
)
-def test_empty_groupby(
- columns, keys, values, method, op, using_array_manager, dropna, using_infer_string
-):
+def test_empty_groupby(columns, keys, values, method, op, dropna, using_infer_string):
# GH8093 & GH26411
override_dtype = None
diff --git a/pandas/tests/groupby/test_reductions.py b/pandas/tests/groupby/test_reductions.py
index 425079f943aba..8333dba439be9 100644
--- a/pandas/tests/groupby/test_reductions.py
+++ b/pandas/tests/groupby/test_reductions.py
@@ -362,7 +362,7 @@ def test_max_min_non_numeric():
assert "ss" in result
-def test_max_min_object_multiple_columns(using_array_manager):
+def test_max_min_object_multiple_columns():
# GH#41111 case where the aggregation is valid for some columns but not
# others; we split object blocks column-wise, consistent with
# DataFrame._reduce
@@ -375,8 +375,7 @@ def test_max_min_object_multiple_columns(using_array_manager):
}
)
df._consolidate_inplace() # should already be consolidate, but double-check
- if not using_array_manager:
- assert len(df._mgr.blocks) == 2
+ assert len(df._mgr.blocks) == 2
gb = df.groupby("A")
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index b97df376ac47f..ca796463f4a1e 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -213,7 +213,7 @@ def test_detect_chained_assignment(self, using_copy_on_write):
@pytest.mark.arm_slow
def test_detect_chained_assignment_raises(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
+ self, using_copy_on_write, warn_copy_on_write
):
# test with the chaining
df = DataFrame(
@@ -236,7 +236,7 @@ def test_detect_chained_assignment_raises(
df["A"][0] = -5
with tm.raises_chained_assignment_error():
df["A"][1] = np.nan
- elif not using_array_manager:
+ else:
with pytest.raises(SettingWithCopyError, match=msg):
with tm.raises_chained_assignment_error():
df["A"][0] = -5
@@ -246,14 +246,6 @@ def test_detect_chained_assignment_raises(
df["A"][1] = np.nan
assert df["A"]._is_copy is None
- else:
- # INFO(ArrayManager) for ArrayManager it doesn't matter that it's
- # a mixed dataframe
- df["A"][0] = -5
- df["A"][1] = -6
- expected = DataFrame([[-5, 2], [-6, 3]], columns=list("AB"))
- expected["B"] = expected["B"].astype("float64")
- tm.assert_frame_equal(df, expected)
@pytest.mark.arm_slow
def test_detect_chained_assignment_fails(
@@ -297,7 +289,7 @@ def test_detect_chained_assignment_doc_example(
@pytest.mark.arm_slow
def test_detect_chained_assignment_object_dtype(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
+ self, using_copy_on_write, warn_copy_on_write
):
expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]})
df = DataFrame(
@@ -317,18 +309,13 @@ def test_detect_chained_assignment_object_dtype(
with tm.raises_chained_assignment_error():
df["A"][0] = 111
tm.assert_frame_equal(df, expected)
- elif not using_array_manager:
+ else:
with pytest.raises(SettingWithCopyError, match=msg):
with tm.raises_chained_assignment_error():
df["A"][0] = 111
df.loc[0, "A"] = 111
tm.assert_frame_equal(df, expected)
- else:
- # INFO(ArrayManager) for ArrayManager it doesn't matter that it's
- # a mixed dataframe
- df["A"][0] = 111
- tm.assert_frame_equal(df, expected)
@pytest.mark.arm_slow
def test_detect_chained_assignment_is_copy_pickle(self):
@@ -453,7 +440,7 @@ def test_detect_chained_assignment_undefined_column(
@pytest.mark.arm_slow
def test_detect_chained_assignment_changing_dtype(
- self, using_array_manager, using_copy_on_write, warn_copy_on_write
+ self, using_copy_on_write, warn_copy_on_write
):
# Mixed type setting but same dtype & changing dtype
df = DataFrame(
@@ -485,15 +472,9 @@ def test_detect_chained_assignment_changing_dtype(
with pytest.raises(SettingWithCopyError, match=msg):
df.loc[2]["C"] = "foo"
- if not using_array_manager:
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["C"][2] = "foo"
- else:
- # INFO(ArrayManager) for ArrayManager it doesn't matter if it's
- # changing the dtype or not
- df["C"][2] = "foo"
- assert df.loc[2, "C"] == "foo"
+ with pytest.raises(SettingWithCopyError, match=msg):
+ with tm.raises_chained_assignment_error():
+ df["C"][2] = "foo"
def test_setting_with_copy_bug(self, using_copy_on_write, warn_copy_on_write):
# operating on a copy
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index 409eca42f404b..a1d8577d534f5 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -72,13 +72,12 @@ class TestiLocBaseIndependent:
],
)
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
- def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manager):
+ def test_iloc_setitem_fullcol_categorical(self, indexer, key):
frame = DataFrame({0: range(3)}, dtype=object)
cat = Categorical(["alpha", "beta", "gamma"])
- if not using_array_manager:
- assert frame._mgr.blocks[0]._can_hold_element(cat)
+ assert frame._mgr.blocks[0]._can_hold_element(cat)
df = frame.copy()
orig_vals = df.values
@@ -86,8 +85,7 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manage
indexer(df)[key, 0] = cat
expected = DataFrame({0: cat}).astype(object)
- if not using_array_manager:
- assert np.shares_memory(df[0].values, orig_vals)
+ assert np.shares_memory(df[0].values, orig_vals)
tm.assert_frame_equal(df, expected)
@@ -520,9 +518,7 @@ def test_iloc_setitem_dups(self):
df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True)
tm.assert_frame_equal(df, expected)
- def test_iloc_setitem_frame_duplicate_columns_multiple_blocks(
- self, using_array_manager
- ):
+ def test_iloc_setitem_frame_duplicate_columns_multiple_blocks(self):
# Same as the "assign back to self" check in test_iloc_setitem_dups
# but on a DataFrame with multiple blocks
df = DataFrame([[0, 1], [2, 3]], columns=["B", "B"])
@@ -530,14 +526,12 @@ def test_iloc_setitem_frame_duplicate_columns_multiple_blocks(
# setting float values that can be held by existing integer arrays
# is inplace
df.iloc[:, 0] = df.iloc[:, 0].astype("f8")
- if not using_array_manager:
- assert len(df._mgr.blocks) == 1
+ assert len(df._mgr.blocks) == 1
# if the assigned values cannot be held by existing integer arrays,
# we cast
df.iloc[:, 0] = df.iloc[:, 0] + 0.5
- if not using_array_manager:
- assert len(df._mgr.blocks) == 2
+ assert len(df._mgr.blocks) == 2
expected = df.copy()
@@ -632,7 +626,7 @@ def test_iloc_getitem_labelled_frame(self):
with pytest.raises(ValueError, match=msg):
df.iloc["j", "D"]
- def test_iloc_getitem_doc_issue(self, using_array_manager):
+ def test_iloc_getitem_doc_issue(self):
# multi axis slicing issue with single block
# surfaced in GH 6059
@@ -662,8 +656,7 @@ def test_iloc_getitem_doc_issue(self, using_array_manager):
columns = list(range(0, 8, 2))
df = DataFrame(arr, index=index, columns=columns)
- if not using_array_manager:
- df._mgr.blocks[0].mgr_locs
+ df._mgr.blocks[0].mgr_locs
result = df.iloc[1:5, 2:4]
expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4])
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index 57f45f867254d..45ec968714aff 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -77,9 +77,7 @@ def test_setitem_ndarray_1d_2(self):
"ignore:Series.__getitem__ treating keys as positions is deprecated:"
"FutureWarning"
)
- def test_getitem_ndarray_3d(
- self, index, frame_or_series, indexer_sli, using_array_manager
- ):
+ def test_getitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
# GH 25567
obj = gen_obj(frame_or_series, index)
idxr = indexer_sli(obj)
@@ -88,12 +86,8 @@ def test_getitem_ndarray_3d(
msgs = []
if frame_or_series is Series and indexer_sli in [tm.setitem, tm.iloc]:
msgs.append(r"Wrong number of dimensions. values.ndim > ndim \[3 > 1\]")
- if using_array_manager:
- msgs.append("Passed array should be 1-dimensional")
if frame_or_series is Series or indexer_sli is tm.iloc:
msgs.append(r"Buffer has wrong number of dimensions \(expected 1, got 3\)")
- if using_array_manager:
- msgs.append("indexer should be 1-dimensional")
if indexer_sli is tm.loc or (
frame_or_series is Series and indexer_sli is tm.setitem
):
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index fb0adc56c401b..da10555e60301 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1490,7 +1490,7 @@ def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture):
result.loc[:, idxer] = expected
tm.assert_frame_equal(result, expected)
- def test_loc_setitem_time_key(self, using_array_manager):
+ def test_loc_setitem_time_key(self):
index = date_range("2012-01-01", "2012-01-05", freq="30min")
df = DataFrame(
np.random.default_rng(2).standard_normal((len(index), 5)), index=index
@@ -1505,9 +1505,6 @@ def test_loc_setitem_time_key(self, using_array_manager):
result = result.loc[akey]
expected = df.loc[akey].copy()
expected.loc[:] = 0
- if using_array_manager:
- # TODO(ArrayManager) we are still overwriting columns
- expected = expected.astype(float)
tm.assert_frame_equal(result, expected)
result = df.copy()
@@ -1520,9 +1517,6 @@ def test_loc_setitem_time_key(self, using_array_manager):
result = result.loc[bkey]
expected = df.loc[bkey].copy()
expected.loc[:] = 0
- if using_array_manager:
- # TODO(ArrayManager) we are still overwriting columns
- expected = expected.astype(float)
tm.assert_frame_equal(result, expected)
result = df.copy()
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index ca551024b4c1f..b0a041ed5b69c 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -279,7 +279,7 @@ def test_partial_setting(self):
s.iat[3] = 5.0
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
- def test_partial_setting_frame(self, using_array_manager):
+ def test_partial_setting_frame(self):
df_orig = DataFrame(
np.arange(6).reshape(3, 2), columns=["A", "B"], dtype="int64"
)
@@ -292,8 +292,6 @@ def test_partial_setting_frame(self, using_array_manager):
df.iloc[4, 2] = 5.0
msg = "index 2 is out of bounds for axis 0 with size 2"
- if using_array_manager:
- msg = "list index out of range"
with pytest.raises(IndexError, match=msg):
df.iat[4, 2] = 5.0
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index e4b94177eedb2..8fc02cc7799ed 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1003,7 +1003,7 @@ def test_filter_row_groups(self, pa):
result = read_parquet(path, pa, filters=[("a", "==", 0)])
assert len(result) == 1
- def test_read_parquet_manager(self, pa, using_array_manager):
+ def test_read_parquet_manager(self, pa):
# ensure that read_parquet honors the pandas.options.mode.data_manager option
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
@@ -1012,10 +1012,7 @@ def test_read_parquet_manager(self, pa, using_array_manager):
with tm.ensure_clean() as path:
df.to_parquet(path, engine=pa)
result = read_parquet(path, pa)
- if using_array_manager:
- assert isinstance(result._mgr, pd.core.internals.ArrayManager)
- else:
- assert isinstance(result._mgr, pd.core.internals.BlockManager)
+ assert isinstance(result._mgr, pd.core.internals.BlockManager)
def test_read_dtype_backend_pyarrow_config(self, pa, df_full):
import pyarrow
diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py
index 81ca227fb7afb..3fb6a3fb61396 100644
--- a/pandas/tests/reshape/concat/test_append.py
+++ b/pandas/tests/reshape/concat/test_append.py
@@ -328,16 +328,13 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self):
result = df._append([ser, ser], ignore_index=True)
tm.assert_frame_equal(result, expected)
- def test_append_empty_tz_frame_with_datetime64ns(self, using_array_manager):
+ def test_append_empty_tz_frame_with_datetime64ns(self):
# https://github.com/pandas-dev/pandas/issues/35460
df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]")
# pd.NaT gets inferred as tz-naive, so append result is tz-naive
result = df._append({"a": pd.NaT}, ignore_index=True)
- if using_array_manager:
- expected = DataFrame({"a": [pd.NaT]}, dtype=object)
- else:
- expected = DataFrame({"a": [np.nan]}, dtype=object)
+ expected = DataFrame({"a": [np.nan]}, dtype=object)
tm.assert_frame_equal(result, expected)
# also test with typed value to append
@@ -356,9 +353,7 @@ def test_append_empty_tz_frame_with_datetime64ns(self, using_array_manager):
"dtype_str", ["datetime64[ns, UTC]", "datetime64[ns]", "Int64", "int64"]
)
@pytest.mark.parametrize("val", [1, "NaT"])
- def test_append_empty_frame_with_timedelta64ns_nat(
- self, dtype_str, val, using_array_manager
- ):
+ def test_append_empty_frame_with_timedelta64ns_nat(self, dtype_str, val):
# https://github.com/pandas-dev/pandas/issues/35460
df = DataFrame(columns=["a"]).astype(dtype_str)
@@ -366,7 +361,7 @@ def test_append_empty_frame_with_timedelta64ns_nat(
result = df._append(other, ignore_index=True)
expected = other.astype(object)
- if isinstance(val, str) and dtype_str != "int64" and not using_array_manager:
+ if isinstance(val, str) and dtype_str != "int64":
# TODO: expected used to be `other.astype(object)` which is a more
# reasonable result. This was changed when tightening
# assert_frame_equal's treatment of mismatched NAs to match the
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py
index 9e34d02091e69..2cc91992f1fd7 100644
--- a/pandas/tests/reshape/concat/test_concat.py
+++ b/pandas/tests/reshape/concat/test_concat.py
@@ -44,7 +44,7 @@ def test_append_concat(self):
assert isinstance(result.index, PeriodIndex)
assert result.index[0] == s1.index[0]
- def test_concat_copy(self, using_array_manager, using_copy_on_write):
+ def test_concat_copy(self, using_copy_on_write):
df = DataFrame(np.random.default_rng(2).standard_normal((4, 3)))
df2 = DataFrame(np.random.default_rng(2).integers(0, 10, size=4).reshape(4, 1))
df3 = DataFrame({5: "foo"}, index=range(4))
@@ -72,18 +72,14 @@ def test_concat_copy(self, using_array_manager, using_copy_on_write):
elif arr.dtype.kind in ["i", "u"]:
assert arr.base is df2._mgr.arrays[0].base
elif arr.dtype == object:
- if using_array_manager:
- # we get the same array object, which has no base
- assert arr is df3._mgr.arrays[0]
- else:
- assert arr.base is not None
+ assert arr.base is not None
# Float block was consolidated.
df4 = DataFrame(np.random.default_rng(2).standard_normal((4, 1)))
result = concat([df, df2, df3, df4], axis=1, copy=False)
for arr in result._mgr.arrays:
if arr.dtype.kind == "f":
- if using_array_manager or using_copy_on_write:
+ if using_copy_on_write:
# this is a view on some array in either df or df4
assert any(
np.shares_memory(arr, other)
diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py
index 71ddff7438254..77485788faa02 100644
--- a/pandas/tests/reshape/concat/test_datetimes.py
+++ b/pandas/tests/reshape/concat/test_datetimes.py
@@ -214,9 +214,7 @@ def test_concat_NaT_dataframes(self, tz):
@pytest.mark.parametrize("tz1", [None, "UTC"])
@pytest.mark.parametrize("tz2", [None, "UTC"])
@pytest.mark.parametrize("item", [pd.NaT, Timestamp("20150101")])
- def test_concat_NaT_dataframes_all_NaT_axis_0(
- self, tz1, tz2, item, using_array_manager
- ):
+ def test_concat_NaT_dataframes_all_NaT_axis_0(self, tz1, tz2, item):
# GH 12396
# tz-naive
@@ -228,7 +226,7 @@ def test_concat_NaT_dataframes_all_NaT_axis_0(
expected = expected.apply(lambda x: x.dt.tz_localize(tz2))
if tz1 != tz2:
expected = expected.astype(object)
- if item is pd.NaT and not using_array_manager:
+ if item is pd.NaT:
# GH#18463
# TODO: setting nan here is to keep the test passing as we
# make assert_frame_equal stricter, but is nan really the
@@ -567,7 +565,7 @@ def test_concat_multiindex_datetime_nat():
tm.assert_frame_equal(result, expected)
-def test_concat_float_datetime64(using_array_manager):
+def test_concat_float_datetime64():
# GH#32934
df_time = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")})
df_float = DataFrame({"A": pd.array([1.0], dtype="float64")})
@@ -592,15 +590,8 @@ def test_concat_float_datetime64(using_array_manager):
result = concat([df_time.iloc[:0], df_float])
tm.assert_frame_equal(result, expected)
- if not using_array_manager:
- expected = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")})
- msg = "The behavior of DataFrame concatenation with empty or all-NA entries"
- with tm.assert_produces_warning(FutureWarning, match=msg):
- result = concat([df_time, df_float.iloc[:0]])
- tm.assert_frame_equal(result, expected)
- else:
- expected = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")}).astype(
- {"A": "object"}
- )
+ expected = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")})
+ msg = "The behavior of DataFrame concatenation with empty or all-NA entries"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
result = concat([df_time, df_float.iloc[:0]])
- tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index d7a343ae9f152..9f832c7b1d1ca 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -316,7 +316,7 @@ def test_merge_copy(self):
merged["d"] = "peekaboo"
assert (right["d"] == "bar").all()
- def test_merge_nocopy(self, using_array_manager):
+ def test_merge_nocopy(self):
left = DataFrame({"a": 0, "b": 1}, index=range(10))
right = DataFrame({"c": "foo", "d": "bar"}, index=range(10))
@@ -702,7 +702,7 @@ def _constructor(self):
assert isinstance(result, NotADataFrame)
- def test_join_append_timedeltas(self, using_array_manager):
+ def test_join_append_timedeltas(self):
# timedelta64 issues with join/merge
# GH 5695
@@ -712,8 +712,6 @@ def test_join_append_timedeltas(self, using_array_manager):
df = DataFrame(columns=list("dt"))
msg = "The behavior of DataFrame concatenation with empty or all-NA entries"
warn = FutureWarning
- if using_array_manager:
- warn = None
with tm.assert_produces_warning(warn, match=msg):
df = concat([df, d], ignore_index=True)
result = concat([df, d], ignore_index=True)
@@ -723,9 +721,6 @@ def test_join_append_timedeltas(self, using_array_manager):
"t": [timedelta(0, 22500), timedelta(0, 22500)],
}
)
- if using_array_manager:
- # TODO(ArrayManager) decide on exact casting rules in concat
- expected = expected.astype(object)
tm.assert_frame_equal(result, expected)
def test_join_append_timedeltas2(self):
diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py
index 136e76986df9d..8a30b63cf0e17 100644
--- a/pandas/tests/reshape/test_crosstab.py
+++ b/pandas/tests/reshape/test_crosstab.py
@@ -459,7 +459,7 @@ def test_crosstab_normalize_arrays(self):
)
tm.assert_frame_equal(test_case, norm_sum)
- def test_crosstab_with_empties(self, using_array_manager):
+ def test_crosstab_with_empties(self):
# Check handling of empties
df = DataFrame(
{
@@ -484,9 +484,6 @@ def test_crosstab_with_empties(self, using_array_manager):
index=Index([1, 2], name="a", dtype="int64"),
columns=Index([3, 4], name="b"),
)
- if using_array_manager:
- # INFO(ArrayManager) column without NaNs can preserve int dtype
- nans[3] = nans[3].astype("int64")
calculated = crosstab(df.a, df.b, values=df.c, aggfunc="count", normalize=False)
tm.assert_frame_equal(nans, calculated)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 18a449b4d0c67..bf2717be4d7ae 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -1277,7 +1277,7 @@ def test_pivot_table_with_margins_set_margin_name(self, margin_name, data):
margins_name=margin_name,
)
- def test_pivot_timegrouper(self, using_array_manager):
+ def test_pivot_timegrouper(self):
df = DataFrame(
{
"Branch": "A A A A A A A B".split(),
@@ -1331,9 +1331,6 @@ def test_pivot_timegrouper(self, using_array_manager):
)
expected.index.name = "Date"
expected.columns.name = "Buyer"
- if using_array_manager:
- # INFO(ArrayManager) column without NaNs can preserve int dtype
- expected["Carl"] = expected["Carl"].astype("int64")
result = pivot_table(
df,
@@ -2370,7 +2367,7 @@ def test_pivot_table_datetime_warning(self):
)
tm.assert_frame_equal(result, expected)
- def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
+ def test_pivot_table_with_mixed_nested_tuples(self):
# GH 50342
df = DataFrame(
{
@@ -2434,9 +2431,6 @@ def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
[["bar", "bar", "foo", "foo"], ["one", "two"] * 2], names=["A", "B"]
),
)
- if using_array_manager:
- # INFO(ArrayManager) column without NaNs can preserve int dtype
- expected["small"] = expected["small"].astype("int64")
tm.assert_frame_equal(result, expected)
def test_pivot_table_aggfunc_nunique_with_different_values(self):
diff --git a/pandas/tests/reshape/test_pivot_multilevel.py b/pandas/tests/reshape/test_pivot_multilevel.py
index 08ef29440825f..2c9d54c3db72c 100644
--- a/pandas/tests/reshape/test_pivot_multilevel.py
+++ b/pandas/tests/reshape/test_pivot_multilevel.py
@@ -197,7 +197,7 @@ def test_pivot_list_like_columns(
tm.assert_frame_equal(result, expected)
-def test_pivot_multiindexed_rows_and_cols(using_array_manager):
+def test_pivot_multiindexed_rows_and_cols():
# GH 36360
df = pd.DataFrame(
@@ -225,9 +225,7 @@ def test_pivot_multiindexed_rows_and_cols(using_array_manager):
),
index=Index([0, 1], dtype="int64", name="idx_L0"),
)
- if not using_array_manager:
- # BlockManager does not preserve the dtypes
- expected = expected.astype("float64")
+ expected = expected.astype("float64")
tm.assert_frame_equal(res, expected)
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index 6f0c8d751a92a..1a4a390da1323 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -318,7 +318,7 @@ def test_reindex_fill_value():
@td.skip_array_manager_not_yet_implemented
@pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"])
@pytest.mark.parametrize("fill_value", ["string", 0, Timedelta(0)])
-def test_reindex_fill_value_datetimelike_upcast(dtype, fill_value, using_array_manager):
+def test_reindex_fill_value_datetimelike_upcast(dtype, fill_value):
# https://github.com/pandas-dev/pandas/issues/42921
if dtype == "timedelta64[ns]" and fill_value == Timedelta(0):
# use the scalar that is not compatible with the dtype for this test
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index da069afe5e709..866bfb995a6d5 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -2187,13 +2187,12 @@ def test_series_constructor_infer_multiindex(self, container, data):
class TestSeriesConstructorInternals:
- def test_constructor_no_pandas_array(self, using_array_manager):
+ def test_constructor_no_pandas_array(self):
ser = Series([1, 2, 3])
result = Series(ser.array)
tm.assert_series_equal(ser, result)
- if not using_array_manager:
- assert isinstance(result._mgr.blocks[0], NumpyBlock)
- assert result._mgr.blocks[0].is_numeric
+ assert isinstance(result._mgr.blocks[0], NumpyBlock)
+ assert result._mgr.blocks[0].is_numeric
@td.skip_array_manager_invalid_test
def test_from_array(self):
diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py
index 76353ab25fca6..e200f7d9933aa 100644
--- a/pandas/tests/series/test_reductions.py
+++ b/pandas/tests/series/test_reductions.py
@@ -163,7 +163,7 @@ def test_validate_stat_keepdims():
np.sum(ser, keepdims=True)
-def test_mean_with_convertible_string_raises(using_array_manager, using_infer_string):
+def test_mean_with_convertible_string_raises(using_infer_string):
# GH#44008
ser = Series(["1", "2"])
if using_infer_string:
@@ -177,19 +177,15 @@ def test_mean_with_convertible_string_raises(using_array_manager, using_infer_st
ser.mean()
df = ser.to_frame()
- if not using_array_manager:
- msg = r"Could not convert \['12'\] to numeric|does not support"
+ msg = r"Could not convert \['12'\] to numeric|does not support"
with pytest.raises(TypeError, match=msg):
df.mean()
-def test_mean_dont_convert_j_to_complex(using_array_manager):
+def test_mean_dont_convert_j_to_complex():
# GH#36703
df = pd.DataFrame([{"db": "J", "numeric": 123}])
- if using_array_manager:
- msg = "Could not convert string 'J' to numeric"
- else:
- msg = r"Could not convert \['J'\] to numeric|does not support"
+ msg = r"Could not convert \['J'\] to numeric|does not support"
with pytest.raises(TypeError, match=msg):
df.mean()
@@ -204,15 +200,14 @@ def test_mean_dont_convert_j_to_complex(using_array_manager):
np.mean(df["db"].astype("string").array)
-def test_median_with_convertible_string_raises(using_array_manager):
+def test_median_with_convertible_string_raises():
# GH#34671 this _could_ return a string "2", but definitely not float 2.0
msg = r"Cannot convert \['1' '2' '3'\] to numeric|does not support"
ser = Series(["1", "2", "3"])
with pytest.raises(TypeError, match=msg):
ser.median()
- if not using_array_manager:
- msg = r"Cannot convert \[\['1' '2' '3'\]\] to numeric|does not support"
+ msg = r"Cannot convert \[\['1' '2' '3'\]\] to numeric|does not support"
df = ser.to_frame()
with pytest.raises(TypeError, match=msg):
df.median()
| This started annoying me while adjusting tests for CoW, so ripping it out already | https://api.github.com/repos/pandas-dev/pandas/pulls/56621 | 2023-12-25T23:45:06Z | 2023-12-26T19:35:02Z | 2023-12-26T19:35:02Z | 2023-12-26T19:41:25Z |
Backport PR #56615 on branch 2.2.x (CI: Fix deprecation warnings) | diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py
index 5e47bcc1c5b0e..9660b283a491b 100644
--- a/pandas/tests/io/parser/common/test_chunksize.py
+++ b/pandas/tests/io/parser/common/test_chunksize.py
@@ -223,7 +223,7 @@ def test_chunks_have_consistent_numerical_type(all_parsers, monkeypatch):
warn = None
if parser.engine == "pyarrow":
warn = DeprecationWarning
- depr_msg = "Passing a BlockManager to DataFrame"
+ depr_msg = "Passing a BlockManager to DataFrame|make_block is deprecated"
with tm.assert_produces_warning(warn, match=depr_msg, check_stacklevel=False):
with monkeypatch.context() as m:
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
@@ -254,7 +254,8 @@ def test_warn_if_chunks_have_mismatched_type(all_parsers):
if parser.engine == "pyarrow":
df = parser.read_csv_check_warnings(
DeprecationWarning,
- "Passing a BlockManager to DataFrame is deprecated",
+ "Passing a BlockManager to DataFrame is deprecated|"
+ "make_block is deprecated",
buf,
check_stacklevel=False,
)
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 4a4ae2b259289..db8b586d22fc0 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -171,7 +171,7 @@ def test_suppress_error_output(all_parsers):
warn = None
if parser.engine == "pyarrow":
warn = DeprecationWarning
- msg = "Passing a BlockManager to DataFrame"
+ msg = "Passing a BlockManager to DataFrame|make_block is deprecated"
with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
result = parser.read_csv(StringIO(data), on_bad_lines="skip")
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index ad7cdad363e78..e4b94177eedb2 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1000,9 +1000,7 @@ def test_filter_row_groups(self, pa):
df = pd.DataFrame({"a": list(range(3))})
with tm.ensure_clean() as path:
df.to_parquet(path, engine=pa)
- result = read_parquet(
- path, pa, filters=[("a", "==", 0)], use_legacy_dataset=False
- )
+ result = read_parquet(path, pa, filters=[("a", "==", 0)])
assert len(result) == 1
def test_read_parquet_manager(self, pa, using_array_manager):
| Backport PR #56615: CI: Fix deprecation warnings | https://api.github.com/repos/pandas-dev/pandas/pulls/56620 | 2023-12-25T20:36:19Z | 2023-12-26T19:32:53Z | 2023-12-26T19:32:53Z | 2023-12-26T19:32:53Z |
TYP: some return types from ruff | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2a070e9a49b97..7f3fc95ce00cc 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -32,6 +32,8 @@ repos:
# TODO: remove autofixe-only rules when they are checked by ruff
name: ruff-selected-autofixes
alias: ruff-selected-autofixes
+ files: ^pandas
+ exclude: ^pandas/tests
args: [--select, "ANN001,ANN2", --fix-only, --exit-non-zero-on-fix]
- repo: https://github.com/jendrikseipp/vulture
rev: 'v2.10'
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index d1481639ca5a0..5ee94b74c527e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -431,7 +431,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| Package | Minimum Version | Changed |
+=================+=================+=========+
-| mypy (dev) | 1.7.1 | X |
+| mypy (dev) | 1.8.0 | X |
+-----------------+-----------------+---------+
| | | X |
+-----------------+-----------------+---------+
diff --git a/environment.yml b/environment.yml
index 74317d47e2e53..58eb69ad1f070 100644
--- a/environment.yml
+++ b/environment.yml
@@ -76,7 +76,7 @@ dependencies:
# code checks
- flake8=6.1.0 # run in subprocess over docstring examples
- - mypy=1.7.1 # pre-commit uses locally installed mypy
+ - mypy=1.8.0 # pre-commit uses locally installed mypy
- tokenize-rt # scripts/check_for_inconsistent_pandas_namespace.py
- pre-commit>=3.6.0
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index e342f76dc724b..800b03707540f 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -4,6 +4,7 @@
from typing import (
TYPE_CHECKING,
Literal,
+ NoReturn,
cast,
)
@@ -143,7 +144,7 @@ def assert_almost_equal(
)
-def _check_isinstance(left, right, cls):
+def _check_isinstance(left, right, cls) -> None:
"""
Helper method for our assert_* methods that ensures that
the two objects being compared have the right type before
@@ -576,7 +577,7 @@ def assert_timedelta_array_equal(
def raise_assert_detail(
obj, message, left, right, diff=None, first_diff=None, index_values=None
-):
+) -> NoReturn:
__tracebackhide__ = True
msg = f"""{obj} are different
@@ -664,7 +665,7 @@ def _get_base(obj):
if left_base is right_base:
raise AssertionError(f"{repr(left_base)} is {repr(right_base)}")
- def _raise(left, right, err_msg):
+ def _raise(left, right, err_msg) -> NoReturn:
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(
diff --git a/pandas/_version.py b/pandas/_version.py
index 5d610b5e1ea7e..f8a960630126d 100644
--- a/pandas/_version.py
+++ b/pandas/_version.py
@@ -386,7 +386,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
return pieces
-def plus_or_dot(pieces):
+def plus_or_dot(pieces) -> str:
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index 4770f403b1bdb..b5861fbaebe9c 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -695,8 +695,8 @@ def visit_Call(self, node, side=None, **kwargs):
if not isinstance(key, ast.keyword):
# error: "expr" has no attribute "id"
raise ValueError(
- "keyword error in function call " # type: ignore[attr-defined]
- f"'{node.func.id}'"
+ "keyword error in function call "
+ f"'{node.func.id}'" # type: ignore[attr-defined]
)
if key.arg:
diff --git a/pandas/io/html.py b/pandas/io/html.py
index 5d5bf079784be..26e71c9546ffd 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -269,7 +269,7 @@ def _attr_getter(self, obj, attr):
# Both lxml and BeautifulSoup have the same implementation:
return obj.get(attr)
- def _href_getter(self, obj):
+ def _href_getter(self, obj) -> str | None:
"""
Return a href if the DOM node contains a child <a> or None.
@@ -392,7 +392,7 @@ def _parse_tables(self, document, match, attrs):
"""
raise AbstractMethodError(self)
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
"""
Return whether an individual DOM node matches a tag
@@ -629,7 +629,7 @@ def _href_getter(self, obj) -> str | None:
def _text_getter(self, obj):
return obj.text
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
return obj.name == tag
def _parse_td(self, row):
@@ -758,7 +758,7 @@ def _parse_tables(self, document, match, kwargs):
raise ValueError(f"No tables found matching regex {repr(pattern)}")
return tables
- def _equals_tag(self, obj, tag):
+ def _equals_tag(self, obj, tag) -> bool:
return obj.tag == tag
def _build_doc(self):
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index ed66e46b300f7..4c490c6b2cda2 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -255,7 +255,7 @@ def __init__(
self.is_copy = None
self._format_axes()
- def _format_axes(self):
+ def _format_axes(self) -> None:
raise AbstractMethodError(self)
def write(self) -> str:
@@ -287,7 +287,7 @@ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
else:
return self.obj
- def _format_axes(self):
+ def _format_axes(self) -> None:
if not self.obj.index.is_unique and self.orient == "index":
raise ValueError(f"Series index must be unique for orient='{self.orient}'")
@@ -304,7 +304,7 @@ def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
obj_to_write = self.obj
return obj_to_write
- def _format_axes(self):
+ def _format_axes(self) -> None:
"""
Try to format axes if they are datelike.
"""
@@ -1193,7 +1193,7 @@ def parse(self):
self._try_convert_types()
return self.obj
- def _parse(self):
+ def _parse(self) -> None:
raise AbstractMethodError(self)
@final
@@ -1217,7 +1217,7 @@ def _convert_axes(self) -> None:
new_axis = Index(new_ser, dtype=new_ser.dtype, copy=False)
setattr(self.obj, axis_name, new_axis)
- def _try_convert_types(self):
+ def _try_convert_types(self) -> None:
raise AbstractMethodError(self)
@final
diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py
index 66a7ccacf675b..890b22154648e 100644
--- a/pandas/io/parsers/arrow_parser_wrapper.py
+++ b/pandas/io/parsers/arrow_parser_wrapper.py
@@ -41,7 +41,7 @@ def __init__(self, src: ReadBuffer[bytes], **kwds) -> None:
self._parse_kwds()
- def _parse_kwds(self):
+ def _parse_kwds(self) -> None:
"""
Validates keywords before passing to pyarrow.
"""
@@ -104,7 +104,7 @@ def _get_pyarrow_options(self) -> None:
] = None # PyArrow raises an exception by default
elif on_bad_lines == ParserBase.BadLineHandleMethod.WARN:
- def handle_warning(invalid_row):
+ def handle_warning(invalid_row) -> str:
warnings.warn(
f"Expected {invalid_row.expected_columns} columns, but found "
f"{invalid_row.actual_columns}: {invalid_row.text}",
@@ -219,7 +219,7 @@ def _finalize_pandas_output(self, frame: DataFrame) -> DataFrame:
raise ValueError(e)
return frame
- def _validate_usecols(self, usecols):
+ def _validate_usecols(self, usecols) -> None:
if lib.is_list_like(usecols) and not all(isinstance(x, str) for x in usecols):
raise ValueError(
"The pyarrow engine does not allow 'usecols' to be integer "
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 50611197ad7dd..1139519d2bcd3 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1707,7 +1707,7 @@ def info(self) -> str:
# ------------------------------------------------------------------------
# private methods
- def _check_if_open(self):
+ def _check_if_open(self) -> None:
if not self.is_open:
raise ClosedFileError(f"{self._path} file is not open!")
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py
index e68f4789f0a06..11b2ed0ee7316 100644
--- a/pandas/io/sas/sas_xport.py
+++ b/pandas/io/sas/sas_xport.py
@@ -288,7 +288,7 @@ def close(self) -> None:
def _get_row(self):
return self.filepath_or_buffer.read(80).decode()
- def _read_header(self):
+ def _read_header(self) -> None:
self.filepath_or_buffer.seek(0)
# read file header
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index b0fa6bc6e90c4..3a58daf681cfb 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1514,7 +1514,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
pass
@@ -2073,7 +2073,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
table = SQLTable(
table_name,
self,
@@ -2433,7 +2433,7 @@ def _create_sql_schema(
keys: list[str] | None = None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
raise NotImplementedError("not implemented for adbc")
@@ -2879,7 +2879,7 @@ def _create_sql_schema(
keys=None,
dtype: DtypeArg | None = None,
schema: str | None = None,
- ):
+ ) -> str:
table = SQLiteTable(
table_name,
self,
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 0f097c6059c7c..a4d8054ea4f8c 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -687,7 +687,7 @@ def __init__(
self._prepare_value_labels()
- def _prepare_value_labels(self):
+ def _prepare_value_labels(self) -> None:
"""Encode value labels."""
self.text_len = 0
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 479a5e19dc1c5..2979903edf360 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -662,7 +662,7 @@ def _ensure_frame(self, data) -> DataFrame:
return data
@final
- def _compute_plot_data(self):
+ def _compute_plot_data(self) -> None:
data = self.data
# GH15079 reconstruct data if by is defined
@@ -699,7 +699,7 @@ def _compute_plot_data(self):
self.data = numeric_data.apply(type(self)._convert_to_ndarray)
- def _make_plot(self, fig: Figure):
+ def _make_plot(self, fig: Figure) -> None:
raise AbstractMethodError(self)
@final
@@ -745,7 +745,7 @@ def _post_plot_logic(self, ax: Axes, data) -> None:
"""Post process for each axes. Overridden in child classes"""
@final
- def _adorn_subplots(self, fig: Figure):
+ def _adorn_subplots(self, fig: Figure) -> None:
"""Common post process unrelated to data"""
if len(self.axes) > 0:
all_axes = self._get_subplots(fig)
@@ -1323,7 +1323,7 @@ def __init__(
c = self.data.columns[c]
self.c = c
- def _make_plot(self, fig: Figure):
+ def _make_plot(self, fig: Figure) -> None:
x, y, c, data = self.x, self.y, self.c, self.data
ax = self.axes[0]
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index a47f622216ef7..cb0b4d549f49e 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -26,7 +26,7 @@
BoolishNoneT = TypeVar("BoolishNoneT", bool, int, None)
-def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
+def _check_arg_length(fname, args, max_fname_arg_count, compat_args) -> None:
"""
Checks whether 'args' has length of at most 'compat_args'. Raises
a TypeError if that is not the case, similar to in Python when a
@@ -46,7 +46,7 @@ def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
)
-def _check_for_default_values(fname, arg_val_dict, compat_args):
+def _check_for_default_values(fname, arg_val_dict, compat_args) -> None:
"""
Check that the keys in `arg_val_dict` are mapped to their
default values as specified in `compat_args`.
@@ -125,7 +125,7 @@ def validate_args(fname, args, max_fname_arg_count, compat_args) -> None:
_check_for_default_values(fname, kwargs, compat_args)
-def _check_for_invalid_keys(fname, kwargs, compat_args):
+def _check_for_invalid_keys(fname, kwargs, compat_args) -> None:
"""
Checks whether 'kwargs' contains any keys that are not
in 'compat_args' and raises a TypeError if there is one.
diff --git a/requirements-dev.txt b/requirements-dev.txt
index cbfb6336b2e16..5a63e59e1db88 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -53,7 +53,7 @@ moto
flask
asv>=0.6.1
flake8==6.1.0
-mypy==1.7.1
+mypy==1.8.0
tokenize-rt
pre-commit>=3.6.0
gitpython
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56617 | 2023-12-25T16:43:41Z | 2023-12-26T19:37:35Z | 2023-12-26T19:37:35Z | 2024-01-17T02:49:58Z |
BUG: Add limit_area to EA ffill/bfill | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 15e98cbb2a4d7..a1ecbe586483e 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -321,7 +321,7 @@ Other enhancements
- :meth:`DataFrame.apply` now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
- :meth:`ExtensionArray._explode` interface method added to allow extension type implementations of the ``explode`` method (:issue:`54833`)
- :meth:`ExtensionArray.duplicated` added to allow extension type implementations of the ``duplicated`` method (:issue:`55255`)
-- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area`` (:issue:`56492`)
+- :meth:`Series.ffill`, :meth:`Series.bfill`, :meth:`DataFrame.ffill`, and :meth:`DataFrame.bfill` have gained the argument ``limit_area``; 3rd party :class:`.ExtensionArray` authors need to add this argument to the method ``_pad_or_backfill`` (:issue:`56492`)
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
- Implemented :meth:`Series.dt` methods and attributes for :class:`ArrowDtype` with ``pyarrow.duration`` type (:issue:`52284`)
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 9ece12cf51a7b..0da121c36644a 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -305,7 +305,12 @@ def _fill_mask_inplace(
func(self._ndarray.T, limit=limit, mask=mask.T)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
mask = self.isna()
if mask.any():
@@ -315,7 +320,7 @@ def _pad_or_backfill(
npvalues = self._ndarray.T
if copy:
npvalues = npvalues.copy()
- func(npvalues, limit=limit, mask=mask.T)
+ func(npvalues, limit=limit, limit_area=limit_area, mask=mask.T)
npvalues = npvalues.T
if copy:
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index d7c4d695e6951..2a2b3f1dcc050 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -1025,13 +1025,18 @@ def dropna(self) -> Self:
return type(self)(pc.drop_null(self._pa_array))
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
if not self._hasna:
# TODO(CoW): Not necessary anymore when CoW is the default
return self.copy()
- if limit is None:
+ if limit is None and limit_area is None:
method = missing.clean_fill_method(method)
try:
if method == "pad":
@@ -1047,7 +1052,9 @@ def _pad_or_backfill(
# TODO(3.0): after EA.fillna 'method' deprecation is enforced, we can remove
# this method entirely.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
@doc(ExtensionArray.fillna)
def fillna(
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index e530b28cba88a..5f3d66d17a9bc 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -70,6 +70,7 @@
unique,
)
from pandas.core.array_algos.quantile import quantile_with_mask
+from pandas.core.missing import _fill_limit_area_1d
from pandas.core.sorting import (
nargminmax,
nargsort,
@@ -957,7 +958,12 @@ def interpolate(
)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
"""
Pad or backfill values, used by Series/DataFrame ffill and bfill.
@@ -1015,6 +1021,12 @@ def _pad_or_backfill(
DeprecationWarning,
stacklevel=find_stack_level(),
)
+ if limit_area is not None:
+ raise NotImplementedError(
+ f"{type(self).__name__} does not implement limit_area "
+ "(added in pandas 2.2). 3rd-party ExtnsionArray authors "
+ "need to add this argument to _pad_or_backfill."
+ )
return self.fillna(method=method, limit=limit)
mask = self.isna()
@@ -1024,6 +1036,8 @@ def _pad_or_backfill(
meth = missing.clean_fill_method(method)
npmask = np.asarray(mask)
+ if limit_area is not None and not npmask.all():
+ _fill_limit_area_1d(npmask, limit_area)
if meth == "pad":
indexer = libalgos.get_fill_indexer(npmask, limit=limit)
return self.take(indexer, allow_fill=True)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 7d2d98f71b38c..febea079527e6 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -891,11 +891,18 @@ def max(self, *, axis: AxisInt | None = None, skipna: bool = True) -> IntervalOr
return obj[indexer]
def _pad_or_backfill( # pylint: disable=useless-parent-delegation
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# TODO(3.0): after EA.fillna 'method' deprecation is enforced, we can remove
# this method entirely.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
def fillna(
self, value=None, method=None, limit: int | None = None, copy: bool = True
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index c1bac9cfcb02f..be7895fdb0275 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -193,7 +193,12 @@ def __getitem__(self, item: PositionalIndexer) -> Self | Any:
return self._simple_new(self._data[item], newmask)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
mask = self._mask
@@ -205,7 +210,21 @@ def _pad_or_backfill(
if copy:
npvalues = npvalues.copy()
new_mask = new_mask.copy()
+ elif limit_area is not None:
+ mask = mask.copy()
func(npvalues, limit=limit, mask=new_mask)
+
+ if limit_area is not None and not mask.all():
+ mask = mask.T
+ neg_mask = ~mask
+ first = neg_mask.argmax()
+ last = len(neg_mask) - neg_mask[::-1].argmax() - 1
+ if limit_area == "inside":
+ new_mask[:first] |= mask[:first]
+ new_mask[last + 1 :] |= mask[last + 1 :]
+ elif limit_area == "outside":
+ new_mask[first + 1 : last] |= mask[first + 1 : last]
+
if copy:
return self._simple_new(npvalues.T, new_mask.T)
else:
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index df5ec356175bf..90a691d1beb69 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -810,12 +810,19 @@ def searchsorted(
return m8arr.searchsorted(npvalue, side=side, sorter=sorter)
def _pad_or_backfill(
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# view as dt64 so we get treated as timelike in core.missing,
# similar to dtl._period_dispatch
dta = self.view("M8[ns]")
- result = dta._pad_or_backfill(method=method, limit=limit, copy=copy)
+ result = dta._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
if copy:
return cast("Self", result.view(self.dtype))
else:
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index db670e1ea4816..b2d2e82c7a81f 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -718,11 +718,18 @@ def isna(self) -> Self: # type: ignore[override]
return type(self)(mask, fill_value=False, dtype=dtype)
def _pad_or_backfill( # pylint: disable=useless-parent-delegation
- self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True
+ self,
+ *,
+ method: FillnaOptions,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ copy: bool = True,
) -> Self:
# TODO(3.0): We can remove this method once deprecation for fillna method
# keyword is enforced.
- return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+ return super()._pad_or_backfill(
+ method=method, limit=limit, limit_area=limit_area, copy=copy
+ )
def fillna(
self,
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 20eff9315bc80..fa409f00e9ff6 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from functools import wraps
+import inspect
import re
from typing import (
TYPE_CHECKING,
@@ -2256,11 +2257,21 @@ def pad_or_backfill(
) -> list[Block]:
values = self.values
+ kwargs: dict[str, Any] = {"method": method, "limit": limit}
+ if "limit_area" in inspect.signature(values._pad_or_backfill).parameters:
+ kwargs["limit_area"] = limit_area
+ elif limit_area is not None:
+ raise NotImplementedError(
+ f"{type(values).__name__} does not implement limit_area "
+ "(added in pandas 2.2). 3rd-party ExtnsionArray authors "
+ "need to add this argument to _pad_or_backfill."
+ )
+
if values.ndim == 2 and axis == 1:
# NDArrayBackedExtensionArray.fillna assumes axis=0
- new_values = values.T._pad_or_backfill(method=method, limit=limit).T
+ new_values = values.T._pad_or_backfill(**kwargs).T
else:
- new_values = values._pad_or_backfill(method=method, limit=limit)
+ new_values = values._pad_or_backfill(**kwargs)
return [self.make_block_same_class(new_values)]
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 0d857f6b21517..cd76883d50541 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -3,10 +3,7 @@
"""
from __future__ import annotations
-from functools import (
- partial,
- wraps,
-)
+from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
@@ -823,6 +820,7 @@ def _interpolate_with_limit_area(
values,
method=method,
limit=limit,
+ limit_area=limit_area,
)
if limit_area == "inside":
@@ -863,27 +861,6 @@ def pad_or_backfill_inplace(
-----
Modifies values in-place.
"""
- if limit_area is not None:
- np.apply_along_axis(
- # error: Argument 1 to "apply_along_axis" has incompatible type
- # "partial[None]"; expected
- # "Callable[..., Union[_SupportsArray[dtype[<nothing>]],
- # Sequence[_SupportsArray[dtype[<nothing>]]],
- # Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]],
- # Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]],
- # Sequence[Sequence[Sequence[Sequence[_
- # SupportsArray[dtype[<nothing>]]]]]]]]"
- partial( # type: ignore[arg-type]
- _interpolate_with_limit_area,
- method=method,
- limit=limit,
- limit_area=limit_area,
- ),
- axis,
- values,
- )
- return
-
transf = (lambda x: x) if axis == 0 else (lambda x: x.T)
# reshape a 1 dim if needed
@@ -897,8 +874,7 @@ def pad_or_backfill_inplace(
func = get_fill_func(method, ndim=2)
# _pad_2d and _backfill_2d both modify tvalues inplace
- func(tvalues, limit=limit)
- return
+ func(tvalues, limit=limit, limit_area=limit_area)
def _fillna_prep(
@@ -909,7 +885,6 @@ def _fillna_prep(
if mask is None:
mask = isna(values)
- mask = mask.view(np.uint8)
return mask
@@ -919,16 +894,23 @@ def _datetimelike_compat(func: F) -> F:
"""
@wraps(func)
- def new_func(values, limit: int | None = None, mask=None):
+ def new_func(
+ values,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ mask=None,
+ ):
if needs_i8_conversion(values.dtype):
if mask is None:
# This needs to occur before casting to int64
mask = isna(values)
- result, mask = func(values.view("i8"), limit=limit, mask=mask)
+ result, mask = func(
+ values.view("i8"), limit=limit, limit_area=limit_area, mask=mask
+ )
return result.view(values.dtype), mask
- return func(values, limit=limit, mask=mask)
+ return func(values, limit=limit, limit_area=limit_area, mask=mask)
return cast(F, new_func)
@@ -937,9 +919,12 @@ def new_func(values, limit: int | None = None, mask=None):
def _pad_1d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
+ if limit_area is not None and not mask.all():
+ _fill_limit_area_1d(mask, limit_area)
algos.pad_inplace(values, mask, limit=limit)
return values, mask
@@ -948,9 +933,12 @@ def _pad_1d(
def _backfill_1d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
+ if limit_area is not None and not mask.all():
+ _fill_limit_area_1d(mask, limit_area)
algos.backfill_inplace(values, mask, limit=limit)
return values, mask
@@ -959,9 +947,12 @@ def _backfill_1d(
def _pad_2d(
values: np.ndarray,
limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:
mask = _fillna_prep(values, mask)
+ if limit_area is not None:
+ _fill_limit_area_2d(mask, limit_area)
if values.size:
algos.pad_2d_inplace(values, mask, limit=limit)
@@ -970,9 +961,14 @@ def _pad_2d(
@_datetimelike_compat
def _backfill_2d(
- values, limit: int | None = None, mask: npt.NDArray[np.bool_] | None = None
+ values,
+ limit: int | None = None,
+ limit_area: Literal["inside", "outside"] | None = None,
+ mask: npt.NDArray[np.bool_] | None = None,
):
mask = _fillna_prep(values, mask)
+ if limit_area is not None:
+ _fill_limit_area_2d(mask, limit_area)
if values.size:
algos.backfill_2d_inplace(values, mask, limit=limit)
@@ -982,6 +978,63 @@ def _backfill_2d(
return values, mask
+def _fill_limit_area_1d(
+ mask: npt.NDArray[np.bool_], limit_area: Literal["outside", "inside"]
+) -> None:
+ """Prepare 1d mask for ffill/bfill with limit_area.
+
+ Caller is responsible for checking at least one value of mask is False.
+ When called, mask will no longer faithfully represent when
+ the corresponding are NA or not.
+
+ Parameters
+ ----------
+ mask : np.ndarray[bool, ndim=1]
+ Mask representing NA values when filling.
+ limit_area : { "outside", "inside" }
+ Whether to limit filling to outside or inside the outer most non-NA value.
+ """
+ neg_mask = ~mask
+ first = neg_mask.argmax()
+ last = len(neg_mask) - neg_mask[::-1].argmax() - 1
+ if limit_area == "inside":
+ mask[:first] = False
+ mask[last + 1 :] = False
+ elif limit_area == "outside":
+ mask[first + 1 : last] = False
+
+
+def _fill_limit_area_2d(
+ mask: npt.NDArray[np.bool_], limit_area: Literal["outside", "inside"]
+) -> None:
+ """Prepare 2d mask for ffill/bfill with limit_area.
+
+ When called, mask will no longer faithfully represent when
+ the corresponding are NA or not.
+
+ Parameters
+ ----------
+ mask : np.ndarray[bool, ndim=1]
+ Mask representing NA values when filling.
+ limit_area : { "outside", "inside" }
+ Whether to limit filling to outside or inside the outer most non-NA value.
+ """
+ neg_mask = ~mask.T
+ if limit_area == "outside":
+ # Identify inside
+ la_mask = (
+ np.maximum.accumulate(neg_mask, axis=0)
+ & np.maximum.accumulate(neg_mask[::-1], axis=0)[::-1]
+ )
+ else:
+ # Identify outside
+ la_mask = (
+ ~np.maximum.accumulate(neg_mask, axis=0)
+ | ~np.maximum.accumulate(neg_mask[::-1], axis=0)[::-1]
+ )
+ mask[la_mask.T] = False
+
+
_fill_methods = {"pad": _pad_1d, "backfill": _backfill_1d}
diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py
index ffb7a24b4b390..dbd6682c12123 100644
--- a/pandas/tests/extension/base/missing.py
+++ b/pandas/tests/extension/base/missing.py
@@ -77,6 +77,28 @@ def test_fillna_limit_pad(self, data_missing):
expected = pd.Series(data_missing.take([1, 1, 1, 0, 1]))
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ arr = data_missing.take(input_ilocs)
+ result = pd.Series(arr).ffill(limit_area=limit_area)
+ expected = pd.Series(data_missing.take(expected_ilocs))
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.filterwarnings(
"ignore:Series.fillna with 'method' is deprecated:FutureWarning"
)
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index 49f29b2194cae..9971f527c14d0 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -156,6 +156,36 @@ def test_fillna_limit_pad(self, data_missing):
):
super().test_fillna_limit_pad(data_missing)
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ msg = "ExtensionArray.fillna 'method' keyword is deprecated"
+ with tm.assert_produces_warning(
+ DeprecationWarning,
+ match=msg,
+ check_stacklevel=False,
+ raise_on_extra_warnings=False,
+ ):
+ msg = "DecimalArray does not implement limit_area"
+ with pytest.raises(NotImplementedError, match=msg):
+ super().test_ffill_limit_area(
+ data_missing, limit_area, input_ilocs, expected_ilocs
+ )
+
def test_fillna_limit_backfill(self, data_missing):
msg = "Series.fillna with 'method' is deprecated"
with tm.assert_produces_warning(
diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py
index d3d9dcc4a4712..31f44f886add7 100644
--- a/pandas/tests/extension/json/array.py
+++ b/pandas/tests/extension/json/array.py
@@ -235,6 +235,10 @@ def _values_for_argsort(self):
frozen = [tuple(x.items()) for x in self]
return construct_1d_object_array_from_listlike(frozen)
+ def _pad_or_backfill(self, *, method, limit=None, copy=True):
+ # GH#56616 - test EA method without limit_area argument
+ return super()._pad_or_backfill(method=method, limit=limit, copy=copy)
+
def make_data():
# TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 5319291f2ea01..9de4f17a27333 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -149,6 +149,29 @@ def test_fillna_frame(self):
"""We treat dictionaries as a mapping in fillna, not a scalar."""
super().test_fillna_frame()
+ @pytest.mark.parametrize(
+ "limit_area, input_ilocs, expected_ilocs",
+ [
+ ("outside", [1, 0, 0, 0, 1], [1, 0, 0, 0, 1]),
+ ("outside", [1, 0, 1, 0, 1], [1, 0, 1, 0, 1]),
+ ("outside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 1]),
+ ("outside", [0, 1, 0, 1, 0], [0, 1, 0, 1, 1]),
+ ("inside", [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [1, 0, 1, 0, 1], [1, 1, 1, 1, 1]),
+ ("inside", [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]),
+ ("inside", [0, 1, 0, 1, 0], [0, 1, 1, 1, 0]),
+ ],
+ )
+ def test_ffill_limit_area(
+ self, data_missing, limit_area, input_ilocs, expected_ilocs
+ ):
+ # GH#56616
+ msg = "JSONArray does not implement limit_area"
+ with pytest.raises(NotImplementedError, match=msg):
+ super().test_ffill_limit_area(
+ data_missing, limit_area, input_ilocs, expected_ilocs
+ )
+
@unhashable
def test_value_counts(self, all_data, dropna):
super().test_value_counts(all_data, dropna)
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index 4131138a7c588..4f661b14ef201 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -858,41 +858,29 @@ def test_pad_backfill_deprecated(func):
@pytest.mark.parametrize(
"data, expected_data, method, kwargs",
(
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan],
"ffill",
{"limit_area": "inside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan],
"ffill",
{"limit_area": "inside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0],
"ffill",
{"limit_area": "outside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan],
"ffill",
{"limit_area": "outside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
(
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
@@ -906,41 +894,29 @@ def test_pad_backfill_deprecated(func):
"ffill",
{"limit_area": "outside", "limit": 1},
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "inside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "inside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "outside"},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
- pytest.param(
+ (
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
[np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
"bfill",
{"limit_area": "outside", "limit": 1},
- marks=pytest.mark.xfail(
- reason="GH#41813 - limit_area applied to the wrong axis"
- ),
),
),
)
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index 89b67ddd9f5b6..0d724779abfda 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -58,6 +58,7 @@
"_iLocIndexer",
# TODO(3.0): GH#55043 - remove upon removal of ArrayManager
"_get_option",
+ "_fill_limit_area_1d",
}
| - [x] closes #41813 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Follow up to #56531.
This is slightly complicated by the `EA.fillna` deprecation.
- If `EA.fillna` is implemented, we raise whenever `limit_area` is not None
- If `EA._pad_or_backfill` is implemented and does not have a `limit_area` arg, we raise when `limit_area` is not None
My plan is to introduce a deprecation in 3.1 whenever `_pad_or_backfill` gets called (regardless of whether `limit_area` is `None`) informing EA authors they need to add this argument. Assuming this is a good way to do, I'll open a tracking issue for this.
For dtypes where the corresponding `mask` is not used after filling (e.g. `NDArrayBackedExtensionArray`), this takes a shortcut by modifying mask prior to filling. Compared to implementing `limit_area` after filling, this saves 1 or 2 copies (depending on the EA) and extra computation, at the cost of making `mask` no longer necessarily represent NA values. | https://api.github.com/repos/pandas-dev/pandas/pulls/56616 | 2023-12-25T14:00:50Z | 2024-01-03T22:14:32Z | 2024-01-03T22:14:32Z | 2024-01-04T03:27:34Z |
CI: Fix deprecation warnings | diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py
index 5e47bcc1c5b0e..9660b283a491b 100644
--- a/pandas/tests/io/parser/common/test_chunksize.py
+++ b/pandas/tests/io/parser/common/test_chunksize.py
@@ -223,7 +223,7 @@ def test_chunks_have_consistent_numerical_type(all_parsers, monkeypatch):
warn = None
if parser.engine == "pyarrow":
warn = DeprecationWarning
- depr_msg = "Passing a BlockManager to DataFrame"
+ depr_msg = "Passing a BlockManager to DataFrame|make_block is deprecated"
with tm.assert_produces_warning(warn, match=depr_msg, check_stacklevel=False):
with monkeypatch.context() as m:
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
@@ -254,7 +254,8 @@ def test_warn_if_chunks_have_mismatched_type(all_parsers):
if parser.engine == "pyarrow":
df = parser.read_csv_check_warnings(
DeprecationWarning,
- "Passing a BlockManager to DataFrame is deprecated",
+ "Passing a BlockManager to DataFrame is deprecated|"
+ "make_block is deprecated",
buf,
check_stacklevel=False,
)
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 4a4ae2b259289..db8b586d22fc0 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -171,7 +171,7 @@ def test_suppress_error_output(all_parsers):
warn = None
if parser.engine == "pyarrow":
warn = DeprecationWarning
- msg = "Passing a BlockManager to DataFrame"
+ msg = "Passing a BlockManager to DataFrame|make_block is deprecated"
with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
result = parser.read_csv(StringIO(data), on_bad_lines="skip")
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index ad7cdad363e78..e4b94177eedb2 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1000,9 +1000,7 @@ def test_filter_row_groups(self, pa):
df = pd.DataFrame({"a": list(range(3))})
with tm.ensure_clean() as path:
df.to_parquet(path, engine=pa)
- result = read_parquet(
- path, pa, filters=[("a", "==", 0)], use_legacy_dataset=False
- )
+ result = read_parquet(path, pa, filters=[("a", "==", 0)])
assert len(result) == 1
def test_read_parquet_manager(self, pa, using_array_manager):
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56615 | 2023-12-24T18:23:39Z | 2023-12-25T20:35:20Z | 2023-12-25T20:35:20Z | 2023-12-25T20:35:23Z |
DEPR: Remove SettingWithCopyWarning | diff --git a/doc/source/reference/testing.rst b/doc/source/reference/testing.rst
index a5d61703aceed..1f164d1aa98b4 100644
--- a/doc/source/reference/testing.rst
+++ b/doc/source/reference/testing.rst
@@ -58,8 +58,6 @@ Exceptions and warnings
errors.PossiblePrecisionLoss
errors.PyperclipException
errors.PyperclipWindowsException
- errors.SettingWithCopyError
- errors.SettingWithCopyWarning
errors.SpecificationError
errors.UndefinedVariableError
errors.UnsortedIndexError
diff --git a/doc/source/user_guide/advanced.rst b/doc/source/user_guide/advanced.rst
index 453536098cfbb..f7ab466e92d93 100644
--- a/doc/source/user_guide/advanced.rst
+++ b/doc/source/user_guide/advanced.rst
@@ -11,13 +11,6 @@ and :ref:`other advanced indexing features <advanced.index_types>`.
See the :ref:`Indexing and Selecting Data <indexing>` for general indexing documentation.
-.. warning::
-
- Whether a copy or a reference is returned for a setting operation may
- depend on the context. This is sometimes called ``chained assignment`` and
- should be avoided. See :ref:`Returning a View versus Copy
- <indexing.view_versus_copy>`.
-
See the :ref:`cookbook<cookbook.selection>` for some advanced strategies.
.. _advanced.hierarchical:
@@ -402,6 +395,7 @@ slicers on a single axis.
Furthermore, you can *set* the values using the following methods.
.. ipython:: python
+ :okwarning:
df2 = dfmi.copy()
df2.loc(axis=0)[:, :, ["C1", "C3"]] = -10
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 7c8d3b9e1c869..24cdbad41fe60 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -29,13 +29,6 @@ this area.
production code, we recommended that you take advantage of the optimized
pandas data access methods exposed in this chapter.
-.. warning::
-
- Whether a copy or a reference is returned for a setting operation, may
- depend on the context. This is sometimes called ``chained assignment`` and
- should be avoided. See :ref:`Returning a View versus Copy
- <indexing.view_versus_copy>`.
-
See the :ref:`MultiIndex / Advanced Indexing <advanced>` for ``MultiIndex`` and more advanced indexing documentation.
See the :ref:`cookbook<cookbook.selection>` for some advanced strategies.
@@ -299,12 +292,6 @@ largely as a convenience since it is such a common operation.
Selection by label
------------------
-.. warning::
-
- Whether a copy or a reference is returned for a setting operation, may depend on the context.
- This is sometimes called ``chained assignment`` and should be avoided.
- See :ref:`Returning a View versus Copy <indexing.view_versus_copy>`.
-
.. warning::
``.loc`` is strict when you present slicers that are not compatible (or convertible) with the index type. For example
@@ -445,12 +432,6 @@ For more information about duplicate labels, see
Selection by position
---------------------
-.. warning::
-
- Whether a copy or a reference is returned for a setting operation, may depend on the context.
- This is sometimes called ``chained assignment`` and should be avoided.
- See :ref:`Returning a View versus Copy <indexing.view_versus_copy>`.
-
pandas provides a suite of methods in order to get **purely integer based indexing**. The semantics follow closely Python and NumPy slicing. These are ``0-based`` indexing. When slicing, the start bound is *included*, while the upper bound is *excluded*. Trying to use a non-integer, even a **valid** label will raise an ``IndexError``.
The ``.iloc`` attribute is the primary access method. The following are valid inputs:
@@ -1722,234 +1703,10 @@ You can assign a custom index to the ``index`` attribute:
df_idx.index = pd.Index([10, 20, 30, 40], name="a")
df_idx
-.. _indexing.view_versus_copy:
-
-Returning a view versus a copy
-------------------------------
-
-.. warning::
-
- :ref:`Copy-on-Write <copy_on_write>`
- will become the new default in pandas 3.0. This means that chained indexing will
- never work. As a consequence, the ``SettingWithCopyWarning`` won't be necessary
- anymore.
- See :ref:`this section <copy_on_write_chained_assignment>`
- for more context.
- We recommend turning Copy-on-Write on to leverage the improvements with
-
- ```
- pd.options.mode.copy_on_write = True
- ```
-
- even before pandas 3.0 is available.
-
-When setting values in a pandas object, care must be taken to avoid what is called
-``chained indexing``. Here is an example.
-
-.. ipython:: python
-
- dfmi = pd.DataFrame([list('abcd'),
- list('efgh'),
- list('ijkl'),
- list('mnop')],
- columns=pd.MultiIndex.from_product([['one', 'two'],
- ['first', 'second']]))
- dfmi
-
-Compare these two access methods:
-
-.. ipython:: python
-
- dfmi['one']['second']
-
-.. ipython:: python
-
- dfmi.loc[:, ('one', 'second')]
-
-These both yield the same results, so which should you use? It is instructive to understand the order
-of operations on these and why method 2 (``.loc``) is much preferred over method 1 (chained ``[]``).
-
-``dfmi['one']`` selects the first level of the columns and returns a DataFrame that is singly-indexed.
-Then another Python operation ``dfmi_with_one['second']`` selects the series indexed by ``'second'``.
-This is indicated by the variable ``dfmi_with_one`` because pandas sees these operations as separate events.
-e.g. separate calls to ``__getitem__``, so it has to treat them as linear operations, they happen one after another.
-
-Contrast this to ``df.loc[:,('one','second')]`` which passes a nested tuple of ``(slice(None),('one','second'))`` to a single call to
-``__getitem__``. This allows pandas to deal with this as a single entity. Furthermore this order of operations *can* be significantly
-faster, and allows one to index *both* axes if so desired.
-
Why does assignment fail when using chained indexing?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-.. warning::
-
- :ref:`Copy-on-Write <copy_on_write>`
- will become the new default in pandas 3.0. This means that chained indexing will
- never work. As a consequence, the ``SettingWithCopyWarning`` won't be necessary
- anymore.
- See :ref:`this section <copy_on_write_chained_assignment>`
- for more context.
- We recommend turning Copy-on-Write on to leverage the improvements with
-
- ```
- pd.options.mode.copy_on_write = True
- ```
-
- even before pandas 3.0 is available.
-
-The problem in the previous section is just a performance issue. What's up with
-the ``SettingWithCopy`` warning? We don't **usually** throw warnings around when
-you do something that might cost a few extra milliseconds!
-
-But it turns out that assigning to the product of chained indexing has
-inherently unpredictable results. To see this, think about how the Python
-interpreter executes this code:
-
-.. code-block:: python
-
- dfmi.loc[:, ('one', 'second')] = value
- # becomes
- dfmi.loc.__setitem__((slice(None), ('one', 'second')), value)
-
-But this code is handled differently:
-
-.. code-block:: python
-
- dfmi['one']['second'] = value
- # becomes
- dfmi.__getitem__('one').__setitem__('second', value)
-
-See that ``__getitem__`` in there? Outside of simple cases, it's very hard to
-predict whether it will return a view or a copy (it depends on the memory layout
-of the array, about which pandas makes no guarantees), and therefore whether
-the ``__setitem__`` will modify ``dfmi`` or a temporary object that gets thrown
-out immediately afterward. **That's** what ``SettingWithCopy`` is warning you
-about!
-
-.. note:: You may be wondering whether we should be concerned about the ``loc``
- property in the first example. But ``dfmi.loc`` is guaranteed to be ``dfmi``
- itself with modified indexing behavior, so ``dfmi.loc.__getitem__`` /
- ``dfmi.loc.__setitem__`` operate on ``dfmi`` directly. Of course,
- ``dfmi.loc.__getitem__(idx)`` may be a view or a copy of ``dfmi``.
-
-Sometimes a ``SettingWithCopy`` warning will arise at times when there's no
-obvious chained indexing going on. **These** are the bugs that
-``SettingWithCopy`` is designed to catch! pandas is probably trying to warn you
-that you've done this:
-
-.. code-block:: python
-
- def do_something(df):
- foo = df[['bar', 'baz']] # Is foo a view? A copy? Nobody knows!
- # ... many lines here ...
- # We don't know whether this will modify df or not!
- foo['quux'] = value
- return foo
-
-Yikes!
-
-.. _indexing.evaluation_order:
-
-Evaluation order matters
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. warning::
-
- :ref:`Copy-on-Write <copy_on_write>`
- will become the new default in pandas 3.0. This means than chained indexing will
- never work. As a consequence, the ``SettingWithCopyWarning`` won't be necessary
- anymore.
- See :ref:`this section <copy_on_write_chained_assignment>`
- for more context.
- We recommend turning Copy-on-Write on to leverage the improvements with
-
- ```
- pd.options.mode.copy_on_write = True
- ```
-
- even before pandas 3.0 is available.
-
-When you use chained indexing, the order and type of the indexing operation
-partially determine whether the result is a slice into the original object, or
-a copy of the slice.
-
-pandas has the ``SettingWithCopyWarning`` because assigning to a copy of a
-slice is frequently not intentional, but a mistake caused by chained indexing
-returning a copy where a slice was expected.
-
-If you would like pandas to be more or less trusting about assignment to a
-chained indexing expression, you can set the :ref:`option <options>`
-``mode.chained_assignment`` to one of these values:
-
-* ``'warn'``, the default, means a ``SettingWithCopyWarning`` is printed.
-* ``'raise'`` means pandas will raise a ``SettingWithCopyError``
- you have to deal with.
-* ``None`` will suppress the warnings entirely.
-
-.. ipython:: python
- :okwarning:
-
- dfb = pd.DataFrame({'a': ['one', 'one', 'two',
- 'three', 'two', 'one', 'six'],
- 'c': np.arange(7)})
-
- # This will show the SettingWithCopyWarning
- # but the frame values will be set
- dfb['c'][dfb['a'].str.startswith('o')] = 42
-
-This however is operating on a copy and will not work.
-
-.. ipython:: python
- :okwarning:
- :okexcept:
-
- with pd.option_context('mode.chained_assignment','warn'):
- dfb[dfb['a'].str.startswith('o')]['c'] = 42
-
-A chained assignment can also crop up in setting in a mixed dtype frame.
-
-.. note::
-
- These setting rules apply to all of ``.loc/.iloc``.
-
-The following is the recommended access method using ``.loc`` for multiple items (using ``mask``) and a single item using a fixed index:
-
-.. ipython:: python
-
- dfc = pd.DataFrame({'a': ['one', 'one', 'two',
- 'three', 'two', 'one', 'six'],
- 'c': np.arange(7)})
- dfd = dfc.copy()
- # Setting multiple items using a mask
- mask = dfd['a'].str.startswith('o')
- dfd.loc[mask, 'c'] = 42
- dfd
-
- # Setting a single item
- dfd = dfc.copy()
- dfd.loc[2, 'a'] = 11
- dfd
-
-The following *can* work at times, but it is not guaranteed to, and therefore should be avoided:
-
-.. ipython:: python
- :okwarning:
-
- dfd = dfc.copy()
- dfd['a'][2] = 111
- dfd
-
-Last, the subsequent example will **not** work at all, and so should be avoided:
-
-.. ipython:: python
- :okwarning:
- :okexcept:
-
- with pd.option_context('mode.chained_assignment','raise'):
- dfd.loc[0]['a'] = 1111
-
-.. warning::
-
- The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid
- assignment. There may be false positives; situations where a chained assignment is inadvertently
- reported.
+:ref:`Copy-on-Write <copy_on_write>` is the new default with pandas 3.0.
+This means than chained indexing will never work.
+See :ref:`this section <copy_on_write_chained_assignment>`
+for more context.
diff --git a/doc/source/whatsnew/v0.13.0.rst b/doc/source/whatsnew/v0.13.0.rst
index f2e29121760ab..a624e81d17db9 100644
--- a/doc/source/whatsnew/v0.13.0.rst
+++ b/doc/source/whatsnew/v0.13.0.rst
@@ -172,7 +172,7 @@ API changes
statistical mode(s) by axis/Series. (:issue:`5367`)
- Chained assignment will now by default warn if the user is assigning to a copy. This can be changed
- with the option ``mode.chained_assignment``, allowed options are ``raise/warn/None``. See :ref:`the docs<indexing.view_versus_copy>`.
+ with the option ``mode.chained_assignment``, allowed options are ``raise/warn/None``.
.. ipython:: python
diff --git a/doc/source/whatsnew/v0.13.1.rst b/doc/source/whatsnew/v0.13.1.rst
index 8c85868e1aedb..483dd15a8467a 100644
--- a/doc/source/whatsnew/v0.13.1.rst
+++ b/doc/source/whatsnew/v0.13.1.rst
@@ -24,8 +24,8 @@ Highlights include:
.. warning::
0.13.1 fixes a bug that was caused by a combination of having numpy < 1.8, and doing
- chained assignment on a string-like array. Please review :ref:`the docs<indexing.view_versus_copy>`,
- chained indexing can have unexpected results and should generally be avoided.
+ chained assignment on a string-like array.
+ Chained indexing can have unexpected results and should generally be avoided.
This would previously segfault:
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 8fa1361cc30c1..f4cd57af105dd 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -383,7 +383,7 @@ Other enhancements
- Added ``validate`` argument to :meth:`DataFrame.join` (:issue:`46622`)
- Added ``numeric_only`` argument to :meth:`.Resampler.sum`, :meth:`.Resampler.prod`, :meth:`.Resampler.min`, :meth:`.Resampler.max`, :meth:`.Resampler.first`, and :meth:`.Resampler.last` (:issue:`46442`)
- ``times`` argument in :class:`.ExponentialMovingWindow` now accepts ``np.timedelta64`` (:issue:`47003`)
-- :class:`.DataError`, :class:`.SpecificationError`, :class:`.SettingWithCopyError`, :class:`.SettingWithCopyWarning`, :class:`.NumExprClobberingError`, :class:`.UndefinedVariableError`, :class:`.IndexingError`, :class:`.PyperclipException`, :class:`.PyperclipWindowsException`, :class:`.CSSWarning`, :class:`.PossibleDataLossError`, :class:`.ClosedFileError`, :class:`.IncompatibilityWarning`, :class:`.AttributeConflictWarning`, :class:`.DatabaseError`, :class:`.PossiblePrecisionLoss`, :class:`.ValueLabelTypeMismatch`, :class:`.InvalidColumnName`, and :class:`.CategoricalConversionWarning` are now exposed in ``pandas.errors`` (:issue:`27656`)
+- :class:`.DataError`, :class:`.SpecificationError`, ``SettingWithCopyError``, ``SettingWithCopyWarning``, :class:`.NumExprClobberingError`, :class:`.UndefinedVariableError`, :class:`.IndexingError`, :class:`.PyperclipException`, :class:`.PyperclipWindowsException`, :class:`.CSSWarning`, :class:`.PossibleDataLossError`, :class:`.ClosedFileError`, :class:`.IncompatibilityWarning`, :class:`.AttributeConflictWarning`, :class:`.DatabaseError`, :class:`.PossiblePrecisionLoss`, :class:`.ValueLabelTypeMismatch`, :class:`.InvalidColumnName`, and :class:`.CategoricalConversionWarning` are now exposed in ``pandas.errors`` (:issue:`27656`)
- Added ``check_like`` argument to :func:`testing.assert_series_equal` (:issue:`47247`)
- Add support for :meth:`.DataFrameGroupBy.ohlc` and :meth:`.SeriesGroupBy.ohlc` for extension array dtypes (:issue:`37493`)
- Allow reading compressed SAS files with :func:`read_sas` (e.g., ``.sas7bdat.gz`` files)
diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py
index 9784303fc0b87..c43d59654b44c 100644
--- a/pandas/_config/__init__.py
+++ b/pandas/_config/__init__.py
@@ -34,11 +34,6 @@ def using_copy_on_write() -> bool:
return True
-def using_nullable_dtypes() -> bool:
- _mode_options = _global_config["mode"]
- return _mode_options["nullable_dtypes"]
-
-
def using_pyarrow_string_dtype() -> bool:
_mode_options = _global_config["future"]
return _mode_options["infer_string"]
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index ebd714f9c14d4..7ae65ba11a752 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -16,8 +16,6 @@
import numpy as np
-from pandas._config import option_context
-
from pandas._libs import lib
from pandas._libs.internals import BlockValuesRefs
from pandas._typing import (
@@ -1076,14 +1074,12 @@ def apply_series_generator(self) -> tuple[ResType, Index]:
results = {}
- 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.func(v, *self.args, **self.kwargs)
- 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)
+ for i, v in enumerate(series_gen):
+ results[i] = self.func(v, *self.args, **self.kwargs)
+ 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/core/frame.py b/pandas/core/frame.py
index b8b5df6e5145b..afa680d064c4a 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1446,12 +1446,8 @@ def style(self) -> Styler:
@Appender(_shared_docs["items"])
def items(self) -> Iterable[tuple[Hashable, Series]]:
- if self.columns.is_unique and hasattr(self, "_item_cache"):
- for k in self.columns:
- yield k, self._get_item_cache(k)
- else:
- for i, k in enumerate(self.columns):
- yield k, self._ixs(i, axis=1)
+ for i, k in enumerate(self.columns):
+ yield k, self._ixs(i, axis=1)
def iterrows(self) -> Iterable[tuple[Hashable, Series]]:
"""
@@ -3921,24 +3917,14 @@ def _ixs(self, i: int, axis: AxisInt = 0) -> Series:
if axis == 0:
new_mgr = self._mgr.fast_xs(i)
- # if we are a copy, mark as such
- copy = isinstance(new_mgr.array, np.ndarray) and new_mgr.array.base is None
result = self._constructor_sliced_from_mgr(new_mgr, axes=new_mgr.axes)
result._name = self.index[i]
- result = result.__finalize__(self)
- result._set_is_copy(self, copy=copy)
- return result
+ return result.__finalize__(self)
# icol
else:
- label = self.columns[i]
-
col_mgr = self._mgr.iget(i)
- result = self._box_col_values(col_mgr, i)
-
- # this is a cached value, mark it so
- result._set_as_cached(label, self)
- return result
+ return self._box_col_values(col_mgr, i)
def _get_column_array(self, i: int) -> ArrayLike:
"""
@@ -3998,7 +3984,7 @@ def __getitem__(self, key):
and key in self.columns
or key in self.columns.drop_duplicates(keep=False)
):
- return self._get_item_cache(key)
+ return self._get_item(key)
elif is_mi and self.columns.is_unique and key in self.columns:
return self._getitem_multilevel(key)
@@ -4037,7 +4023,7 @@ def __getitem__(self, key):
if isinstance(indexer, slice):
return self._slice(indexer, axis=1)
- data = self._take_with_is_copy(indexer, axis=1)
+ data = self.take(indexer, axis=1)
if is_single_key:
# What does looking for a single key in a non-unique index return?
@@ -4046,7 +4032,7 @@ def __getitem__(self, key):
# - we have a MultiIndex on columns (test on self.columns, #21309)
if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):
# GH#26490 using data[key] can cause RecursionError
- return data._get_item_cache(key)
+ return data._get_item(key)
return data
@@ -4075,7 +4061,7 @@ def _getitem_bool_array(self, key):
return self.copy(deep=None)
indexer = key.nonzero()[0]
- return self._take_with_is_copy(indexer, axis=0)
+ return self.take(indexer, axis=0)
def _getitem_multilevel(self, key):
# self.columns is a MultiIndex
@@ -4105,7 +4091,6 @@ def _getitem_multilevel(self, key):
result, index=self.index, name=key
)
- result._set_is_copy(self)
return result
else:
# loc is neither a slice nor ndarray, so must be an int
@@ -4134,7 +4119,7 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar:
series = self._ixs(col, axis=1)
return series._values[index]
- series = self._get_item_cache(col)
+ series = self._get_item(col)
engine = self.index._engine
if not isinstance(self.index, MultiIndex):
@@ -4226,7 +4211,6 @@ def _setitem_slice(self, key: slice, value) -> None:
# NB: we can't just use self.loc[key] = value because that
# operates on labels and we need to operate positional for
# backwards-compat, xref GH#31469
- self._check_setitem_copy()
self.iloc[key] = value
def _setitem_array(self, key, value):
@@ -4239,7 +4223,6 @@ def _setitem_array(self, key, value):
)
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
- self._check_setitem_copy()
if isinstance(value, DataFrame):
# GH#39931 reindex since iloc does not align
value = value.reindex(self.index.take(indexer))
@@ -4326,7 +4309,6 @@ def _setitem_frame(self, key, value) -> None:
"Must pass DataFrame or 2-d ndarray with boolean values only"
)
- self._check_setitem_copy()
self._where(-key, value, inplace=True)
def _set_item_frame_value(self, key, value: DataFrame) -> None:
@@ -4388,7 +4370,6 @@ def _iset_item_mgr(
) -> None:
# when called from _set_item_mgr loc can be anything returned from get_loc
self._mgr.iset(loc, value, inplace=inplace, refs=refs)
- self._clear_item_cache()
def _set_item_mgr(
self, key, value: ArrayLike, refs: BlockValuesRefs | None = None
@@ -4401,12 +4382,6 @@ def _set_item_mgr(
else:
self._iset_item_mgr(loc, value, refs=refs)
- # check if we are modifying a copy
- # try to set first as we want an invalid
- # value exception to occur first
- if len(self):
- self._check_setitem_copy()
-
def _iset_item(self, loc: int, value: Series, inplace: bool = True) -> None:
# We are only called from _replace_columnwise which guarantees that
# no reindex is necessary
@@ -4417,12 +4392,6 @@ def _iset_item(self, loc: int, value: Series, inplace: bool = True) -> None:
else:
self._iset_item_mgr(loc, value._values.copy(), inplace=True)
- # check if we are modifying a copy
- # try to set first as we want an invalid
- # value exception to occur first
- if len(self):
- self._check_setitem_copy()
-
def _set_item(self, key, value) -> None:
"""
Add series to DataFrame in specified column.
@@ -4473,7 +4442,6 @@ def _set_value(
icol = self.columns.get_loc(col)
iindex = self.index.get_loc(index)
self._mgr.column_setitem(icol, iindex, value, inplace_only=True)
- self._clear_item_cache()
except (KeyError, TypeError, ValueError, LossySetitemError):
# get_loc might raise a KeyError for missing labels (falling back
@@ -4485,7 +4453,6 @@ def _set_value(
self.iloc[index, col] = value
else:
self.loc[index, col] = value
- self._item_cache.pop(col, None)
except InvalidIndexError as ii_err:
# GH48729: Seems like you are trying to assign a value to a
@@ -4529,50 +4496,9 @@ def _box_col_values(self, values: SingleBlockManager, loc: int) -> Series:
obj._name = name
return obj.__finalize__(self)
- # ----------------------------------------------------------------------
- # Lookup Caching
-
- def _clear_item_cache(self) -> None:
- self._item_cache.clear()
-
- def _get_item_cache(self, item: Hashable) -> Series:
- """Return the cached item, item represents a label indexer."""
- if using_copy_on_write():
- loc = self.columns.get_loc(item)
- return self._ixs(loc, axis=1)
-
- cache = self._item_cache
- res = cache.get(item)
- if res is None:
- # All places that call _get_item_cache have unique columns,
- # pending resolution of GH#33047
-
- loc = self.columns.get_loc(item)
- res = self._ixs(loc, axis=1)
-
- cache[item] = res
-
- # for a chain
- res._is_copy = self._is_copy
- return res
-
- def _reset_cacher(self) -> None:
- # no-op for DataFrame
- pass
-
- def _maybe_cache_changed(self, item, value: Series, inplace: bool) -> None:
- """
- The object has called back to us saying maybe it has changed.
- """
- loc = self._info_axis.get_loc(item)
- arraylike = value._values
-
- old = self._ixs(loc, axis=1)
- if old._values is value._values and inplace:
- # GH#46149 avoid making unnecessary copies/block-splitting
- return
-
- self._mgr.iset(loc, arraylike, inplace=inplace)
+ def _get_item(self, item: Hashable) -> Series:
+ loc = self.columns.get_loc(item)
+ return self._ixs(loc, axis=1)
# ----------------------------------------------------------------------
# Unsorted
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 490a47d16871c..7433a4138da0b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5,7 +5,6 @@
from copy import deepcopy
import datetime as dt
from functools import partial
-import gc
from json import loads
import operator
import pickle
@@ -23,7 +22,6 @@
overload,
)
import warnings
-import weakref
import numpy as np
@@ -98,8 +96,6 @@
AbstractMethodError,
ChainedAssignmentError,
InvalidIndexError,
- SettingWithCopyError,
- SettingWithCopyWarning,
)
from pandas.errors.cow import (
_chained_assignment_method_msg,
@@ -253,10 +249,8 @@ class NDFrame(PandasObject, indexing.IndexingMixin):
_internal_names: list[str] = [
"_mgr",
- "_cacher",
"_item_cache",
"_cache",
- "_is_copy",
"_name",
"_metadata",
"_flags",
@@ -265,7 +259,6 @@ class NDFrame(PandasObject, indexing.IndexingMixin):
_accessors: set[str] = set()
_hidden_attrs: frozenset[str] = frozenset([])
_metadata: list[str] = []
- _is_copy: weakref.ReferenceType[NDFrame] | str | None = None
_mgr: Manager
_attrs: dict[Hashable, Any]
_typ: str
@@ -274,9 +267,7 @@ class NDFrame(PandasObject, indexing.IndexingMixin):
# Constructors
def __init__(self, data: Manager) -> None:
- object.__setattr__(self, "_is_copy", None)
object.__setattr__(self, "_mgr", data)
- object.__setattr__(self, "_item_cache", {})
object.__setattr__(self, "_attrs", {})
object.__setattr__(self, "_flags", Flags(self, allows_duplicate_labels=True))
@@ -788,7 +779,6 @@ def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None:
"""
labels = ensure_index(labels)
self._mgr.set_axis(axis, labels)
- self._clear_item_cache()
@final
def swapaxes(self, axis1: Axis, axis2: Axis, copy: bool_t | None = None) -> Self:
@@ -1106,7 +1096,6 @@ def _rename(
new_index = ax._transform_index(f, level=level)
result._set_axis_nocheck(new_index, axis=axis_no, inplace=True, copy=False)
- result._clear_item_cache()
if inplace:
self._update_inplace(result)
@@ -2194,8 +2183,6 @@ def __setstate__(self, state) -> None:
elif len(state) == 2:
raise NotImplementedError("Pre-0.12 pickles are no longer supported")
- self._item_cache: dict[Hashable, Series] = {}
-
# ----------------------------------------------------------------------
# Rendering Methods
@@ -3963,44 +3950,6 @@ def to_csv(
storage_options=storage_options,
)
- # ----------------------------------------------------------------------
- # Lookup Caching
-
- def _reset_cacher(self) -> None:
- """
- Reset the cacher.
- """
- raise AbstractMethodError(self)
-
- def _maybe_update_cacher(
- self,
- clear: bool_t = False,
- verify_is_copy: bool_t = True,
- inplace: bool_t = False,
- ) -> None:
- """
- See if we need to update our parent cacher if clear, then clear our
- cache.
-
- Parameters
- ----------
- clear : bool, default False
- Clear the item cache.
- verify_is_copy : bool, default True
- Provide is_copy checks.
- """
- if using_copy_on_write():
- return
-
- if verify_is_copy:
- self._check_setitem_copy(t="referent")
-
- if clear:
- self._clear_item_cache()
-
- def _clear_item_cache(self) -> None:
- raise AbstractMethodError(self)
-
# ----------------------------------------------------------------------
# Indexing Methods
@@ -4119,23 +4068,6 @@ class max_speed
self, method="take"
)
- @final
- def _take_with_is_copy(self, indices, axis: Axis = 0) -> Self:
- """
- Internal version of the `take` method that sets the `_is_copy`
- attribute to keep track of the parent dataframe (using in indexing
- for the SettingWithCopyWarning).
-
- For Series this does the same as the public take (it never sets `_is_copy`).
-
- See the docstring of `take` for full explanation of the parameters.
- """
- result = self.take(indices=indices, axis=axis)
- # Maybe set copy if we didn't actually change the index.
- if self.ndim == 2 and not result._get_axis(axis).equals(self._get_axis(axis)):
- result._set_is_copy(self)
- return result
-
@final
def xs(
self,
@@ -4283,9 +4215,9 @@ class animal locomotion
if isinstance(loc, np.ndarray):
if loc.dtype == np.bool_:
(inds,) = loc.nonzero()
- return self._take_with_is_copy(inds, axis=axis)
+ return self.take(inds, axis=axis)
else:
- return self._take_with_is_copy(loc, axis=axis)
+ return self.take(loc, axis=axis)
if not is_scalar(loc):
new_index = index[loc]
@@ -4311,9 +4243,6 @@ class animal locomotion
result = self.iloc[loc]
result.index = new_index
- # this could be a view
- # but only in a single-dtyped view sliceable case
- result._set_is_copy(self, copy=not result._is_view)
return result
def __getitem__(self, item):
@@ -4349,111 +4278,8 @@ def _slice(self, slobj: slice, axis: AxisInt = 0) -> Self:
new_mgr = self._mgr.get_slice(slobj, axis=axis)
result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
result = result.__finalize__(self)
-
- # this could be a view
- # but only in a single-dtyped view sliceable case
- is_copy = axis != 0 or result._is_view
- result._set_is_copy(self, copy=is_copy)
return result
- @final
- def _set_is_copy(self, ref: NDFrame, copy: bool_t = True) -> None:
- if not copy:
- self._is_copy = None
- else:
- assert ref is not None
- self._is_copy = weakref.ref(ref)
-
- def _check_is_chained_assignment_possible(self) -> bool_t:
- """
- Check if we are a view, have a cacher, and are of mixed type.
- If so, then force a setitem_copy check.
-
- Should be called just near setting a value
-
- Will return a boolean if it we are a view and are cached, but a
- single-dtype meaning that the cacher should be updated following
- setting.
- """
- if self._is_copy:
- self._check_setitem_copy(t="referent")
- return False
-
- @final
- def _check_setitem_copy(self, t: str = "setting", force: bool_t = False) -> None:
- """
-
- Parameters
- ----------
- t : str, the type of setting error
- force : bool, default False
- If True, then force showing an error.
-
- validate if we are doing a setitem on a chained copy.
-
- It is technically possible to figure out that we are setting on
- a copy even WITH a multi-dtyped pandas object. In other words, some
- blocks may be views while other are not. Currently _is_view will ALWAYS
- return False for multi-blocks to avoid having to handle this case.
-
- df = DataFrame(np.arange(0,9), columns=['count'])
- df['group'] = 'b'
-
- # This technically need not raise SettingWithCopy if both are view
- # (which is not generally guaranteed but is usually True. However,
- # this is in general not a good practice and we recommend using .loc.
- df.iloc[0:5]['group'] = 'a'
-
- """
- if using_copy_on_write():
- return
-
- # return early if the check is not needed
- if not (force or self._is_copy):
- return
-
- value = config.get_option("mode.chained_assignment")
- if value is None:
- return
-
- # see if the copy is not actually referred; if so, then dissolve
- # the copy weakref
- if self._is_copy is not None and not isinstance(self._is_copy, str):
- r = self._is_copy()
- if not gc.get_referents(r) or (r is not None and r.shape == self.shape):
- self._is_copy = None
- return
-
- # a custom message
- if isinstance(self._is_copy, str):
- t = self._is_copy
-
- elif t == "referent":
- t = (
- "\n"
- "A value is trying to be set on a copy of a slice from a "
- "DataFrame\n\n"
- "See the caveats in the documentation: "
- "https://pandas.pydata.org/pandas-docs/stable/user_guide/"
- "indexing.html#returning-a-view-versus-a-copy"
- )
-
- else:
- t = (
- "\n"
- "A value is trying to be set on a copy of a slice from a "
- "DataFrame.\n"
- "Try using .loc[row_indexer,col_indexer] = value "
- "instead\n\nSee the caveats in the documentation: "
- "https://pandas.pydata.org/pandas-docs/stable/user_guide/"
- "indexing.html#returning-a-view-versus-a-copy"
- )
-
- if value == "raise":
- raise SettingWithCopyError(t)
- if value == "warn":
- warnings.warn(t, SettingWithCopyWarning, stacklevel=find_stack_level())
-
@final
def __delitem__(self, key) -> None:
"""
@@ -4486,12 +4312,6 @@ def __delitem__(self, key) -> None:
loc = self.axes[-1].get_loc(key)
self._mgr = self._mgr.idelete(loc)
- # delete from the caches
- try:
- del self._item_cache[key]
- except KeyError:
- pass
-
# ----------------------------------------------------------------------
# Unsorted
@@ -4861,22 +4681,17 @@ def _drop_axis(
return result.__finalize__(self)
@final
- def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None:
+ def _update_inplace(self, result) -> None:
"""
Replace self internals with result.
Parameters
----------
result : same type as self
- verify_is_copy : bool, default True
- Provide is_copy checks.
"""
# NOTE: This does *not* call __finalize__ and that's an explicit
# decision that we may revisit in the future.
- self._reset_cache()
- self._clear_item_cache()
self._mgr = result._mgr
- self._maybe_update_cacher(verify_is_copy=verify_is_copy, inplace=True)
@final
def add_prefix(self, prefix: str, axis: Axis | None = None) -> Self:
@@ -6352,26 +6167,11 @@ def _dir_additions(self) -> set[str]:
# ----------------------------------------------------------------------
# Consolidation of internals
- @final
- def _protect_consolidate(self, f):
- """
- Consolidate _mgr -- if the blocks have changed, then clear the
- cache
- """
- blocks_before = len(self._mgr.blocks)
- result = f()
- if len(self._mgr.blocks) != blocks_before:
- self._clear_item_cache()
- return result
-
@final
def _consolidate_inplace(self) -> None:
"""Consolidate data in place and return None"""
- def f() -> None:
- self._mgr = self._mgr.consolidate()
-
- self._protect_consolidate(f)
+ self._mgr = self._mgr.consolidate()
@final
def _consolidate(self):
@@ -6383,8 +6183,7 @@ def _consolidate(self):
-------
consolidated : same type as caller
"""
- f = lambda: self._mgr.consolidate()
- cons_data = self._protect_consolidate(f)
+ cons_data = self._mgr.consolidate()
return self._constructor_from_mgr(cons_data, axes=cons_data.axes).__finalize__(
self
)
@@ -6790,7 +6589,6 @@ def copy(self, deep: bool_t | None = True) -> Self:
dtype: object
"""
data = self._mgr.copy(deep=deep)
- self._clear_item_cache()
return self._constructor_from_mgr(data, axes=data.axes).__finalize__(
self, method="copy"
)
@@ -9183,7 +8981,7 @@ def at_time(self, time, asof: bool_t = False, axis: Axis | None = None) -> Self:
raise TypeError("Index must be DatetimeIndex")
indexer = index.indexer_at_time(time, asof=asof)
- return self._take_with_is_copy(indexer, axis=axis)
+ return self.take(indexer, axis=axis)
@final
def between_time(
@@ -9268,7 +9066,7 @@ def between_time(
include_start=left_inclusive,
include_end=right_inclusive,
)
- return self._take_with_is_copy(indexer, axis=axis)
+ return self.take(indexer, axis=axis)
@final
@doc(klass=_shared_doc_kwargs["klass"])
@@ -12481,14 +12279,9 @@ def _inplace_method(self, other, op) -> Self:
"""
result = op(self, other)
- # Delete cacher
- self._reset_cacher()
-
# this makes sure that we are aligned like the input
- # we are updating inplace so we want to ignore is_copy
- self._update_inplace(
- result.reindex_like(self, copy=False), verify_is_copy=False
- )
+ # we are updating inplace
+ self._update_inplace(result.reindex_like(self, copy=False))
return self
@final
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 64f882e5a146c..fa79b23b8209e 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -34,8 +34,6 @@ class providing the base-class of operations.
import numpy as np
-from pandas._config.config import option_context
-
from pandas._libs import (
Timestamp,
lib,
@@ -1742,32 +1740,28 @@ def f(g):
if not include_groups:
return self._python_apply_general(f, self._obj_with_exclusions)
- # ignore SettingWithCopy here in case the user mutates
- with option_context("mode.chained_assignment", None):
- try:
- result = self._python_apply_general(f, self._selected_obj)
- if (
- not isinstance(self.obj, Series)
- and self._selection is None
- and self._selected_obj.shape != self._obj_with_exclusions.shape
- ):
- warnings.warn(
- message=_apply_groupings_depr.format(
- type(self).__name__, "apply"
- ),
- category=DeprecationWarning,
- stacklevel=find_stack_level(),
- )
- except TypeError:
- # gh-20949
- # try again, with .apply acting as a filtering
- # operation, by excluding the grouping column
- # This would normally not be triggered
- # except if the udf is trying an operation that
- # fails on *some* columns, e.g. a numeric operation
- # on a string grouper column
-
- return self._python_apply_general(f, self._obj_with_exclusions)
+ try:
+ result = self._python_apply_general(f, self._selected_obj)
+ if (
+ not isinstance(self.obj, Series)
+ and self._selection is None
+ and self._selected_obj.shape != self._obj_with_exclusions.shape
+ ):
+ warnings.warn(
+ message=_apply_groupings_depr.format(type(self).__name__, "apply"),
+ category=DeprecationWarning,
+ stacklevel=find_stack_level(),
+ )
+ except TypeError:
+ # gh-20949
+ # try again, with .apply acting as a filtering
+ # operation, by excluding the grouping column
+ # This would normally not be triggered
+ # except if the udf is trying an operation that
+ # fails on *some* columns, e.g. a numeric operation
+ # on a string grouper column
+
+ return self._python_apply_general(f, self._obj_with_exclusions)
return result
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 7e3ba4089ff60..1a24ae8530c12 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -106,16 +106,7 @@ def _delegate_property_get(self, name: str):
else:
index = self._parent.index
# return the result as a Series
- result = Series(result, index=index, name=self.name).__finalize__(self._parent)
-
- # setting this object will show a SettingWithCopyWarning/Error
- result._is_copy = (
- "modifications to a property of a datetimelike "
- "object are not supported and are discarded. "
- "Change values on the original."
- )
-
- return result
+ return Series(result, index=index, name=self.name).__finalize__(self._parent)
def _delegate_property_set(self, name: str, value, *args, **kwargs):
raise ValueError(
@@ -134,19 +125,10 @@ def _delegate_method(self, name: str, *args, **kwargs):
if not is_list_like(result):
return result
- result = Series(result, index=self._parent.index, name=self.name).__finalize__(
+ return Series(result, index=self._parent.index, name=self.name).__finalize__(
self._parent
)
- # setting this object will show a SettingWithCopyWarning/Error
- result._is_copy = (
- "modifications to a method of a datetimelike "
- "object are not supported and are discarded. "
- "Change values on the original."
- )
-
- return result
-
@delegate_names(
delegate=ArrowExtensionArray,
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index b58c3179dec09..ab06dd3ea5af0 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1194,7 +1194,7 @@ def _getbool_axis(self, key, axis: AxisInt):
labels = self.obj._get_axis(axis)
key = check_bool_indexer(labels, key)
inds = key.nonzero()[0]
- return self.obj._take_with_is_copy(inds, axis=axis)
+ return self.obj.take(inds, axis=axis)
@doc(IndexingMixin.loc)
@@ -1697,7 +1697,7 @@ def _get_list_axis(self, key, axis: AxisInt):
`axis` can only be zero.
"""
try:
- return self.obj._take_with_is_copy(key, axis=axis)
+ return self.obj.take(key, axis=axis)
except IndexError as err:
# re-raise with different error message, e.g. test_getitem_ndarray_3d
raise IndexError("positional indexers are out-of-bounds") from err
@@ -1905,8 +1905,6 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc") -> None:
reindexers, allow_dups=True
)
self.obj._mgr = new_obj._mgr
- self.obj._maybe_update_cacher(clear=True)
- self.obj._is_copy = None
nindexer.append(labels.get_loc(key))
@@ -2154,8 +2152,6 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None:
# falling back to casting if necessary)
self.obj._mgr.column_setitem(loc, plane_indexer, value)
- self.obj._clear_item_cache()
-
def _setitem_single_block(self, indexer, value, name: str) -> None:
"""
_setitem_with_indexer for the case when we have a single Block.
@@ -2191,12 +2187,8 @@ def _setitem_single_block(self, indexer, value, name: str) -> None:
if isinstance(value, ABCDataFrame) and name != "iloc":
value = self._align_frame(indexer, value)._values
- # check for chained assignment
- self.obj._check_is_chained_assignment_possible()
-
# actually do the set
self.obj._mgr = self.obj._mgr.setitem(indexer=indexer, value=value)
- self.obj._maybe_update_cacher(clear=True, inplace=True)
def _setitem_with_indexer_missing(self, indexer, value):
"""
@@ -2262,7 +2254,6 @@ def _setitem_with_indexer_missing(self, indexer, value):
self.obj._mgr = self.obj._constructor(
new_values, index=new_index, name=self.obj.name
)._mgr
- self.obj._maybe_update_cacher(clear=True)
elif self.ndim == 2:
if not len(self.obj.columns):
@@ -2306,7 +2297,6 @@ def _setitem_with_indexer_missing(self, indexer, value):
self.obj._mgr = df._mgr
else:
self.obj._mgr = self.obj._append(value)._mgr
- self.obj._maybe_update_cacher(clear=True)
def _ensure_iterable_column_indexer(self, column_indexer):
"""
diff --git a/pandas/core/interchange/from_dataframe.py b/pandas/core/interchange/from_dataframe.py
index 73f492c83c2ff..390f5e0d0d5ae 100644
--- a/pandas/core/interchange/from_dataframe.py
+++ b/pandas/core/interchange/from_dataframe.py
@@ -10,7 +10,6 @@
import numpy as np
from pandas.compat._optional import import_optional_dependency
-from pandas.errors import SettingWithCopyError
import pandas as pd
from pandas.core.interchange.dataframe_protocol import (
@@ -548,9 +547,5 @@ def set_nulls(
# cast the `data` to nullable float dtype.
data = data.astype(float)
data[null_pos] = None
- except SettingWithCopyError:
- # `SettingWithCopyError` may happen for datetime-like with missing values.
- data = data.copy()
- data[null_pos] = None
return data
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index fa54fde2ece84..5a8a14168d504 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -690,7 +690,7 @@ def is_view(self) -> bool:
# e.g. [ b.values.base is not None for b in self.blocks ]
# but then we have the case of possibly some blocks being a view
# and some blocks not. setting in theory is possible on the non-view
- # blocks w/o causing a SettingWithCopy raise/warn. But this is a bit
+ # blocks. But this is a bit
# complicated
return False
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 94be7bdbaca16..e9d340237c234 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -22,7 +22,6 @@
overload,
)
import warnings
-import weakref
import numpy as np
@@ -1239,7 +1238,6 @@ def __setitem__(self, key, value) -> None:
check_dict_or_set_indexers(key)
key = com.apply_if_callable(key, self)
- cacher_needs_updating = self._check_is_chained_assignment_possible()
if key is Ellipsis:
key = slice(None)
@@ -1317,9 +1315,6 @@ def __setitem__(self, key, value) -> None:
else:
self._set_with(key, value)
- if cacher_needs_updating:
- self._maybe_update_cacher(inplace=True)
-
def _set_with_engine(self, key, value) -> None:
loc = self.index.get_loc(key)
@@ -1371,7 +1366,6 @@ def _set_values(self, key, value) -> None:
key = key._values
self._mgr = self._mgr.setitem(indexer=key, value=value)
- self._maybe_update_cacher()
def _set_value(self, label, value, takeable: bool = False) -> None:
"""
@@ -1400,84 +1394,6 @@ def _set_value(self, label, value, takeable: bool = False) -> None:
self._set_values(loc, value)
- # ----------------------------------------------------------------------
- # Lookup Caching
-
- @property
- def _is_cached(self) -> bool:
- """Return boolean indicating if self is cached or not."""
- return getattr(self, "_cacher", None) is not None
-
- def _get_cacher(self):
- """return my cacher or None"""
- cacher = getattr(self, "_cacher", None)
- if cacher is not None:
- cacher = cacher[1]()
- return cacher
-
- def _reset_cacher(self) -> None:
- """
- Reset the cacher.
- """
- if hasattr(self, "_cacher"):
- del self._cacher
-
- def _set_as_cached(self, item, cacher) -> None:
- """
- Set the _cacher attribute on the calling object with a weakref to
- cacher.
- """
- if using_copy_on_write():
- return
- self._cacher = (item, weakref.ref(cacher))
-
- def _clear_item_cache(self) -> None:
- # no-op for Series
- pass
-
- def _check_is_chained_assignment_possible(self) -> bool:
- """
- See NDFrame._check_is_chained_assignment_possible.__doc__
- """
- if self._is_view and self._is_cached:
- ref = self._get_cacher()
- if ref is not None and ref._is_mixed_type:
- self._check_setitem_copy(t="referent", force=True)
- return True
- return super()._check_is_chained_assignment_possible()
-
- def _maybe_update_cacher(
- self, clear: bool = False, verify_is_copy: bool = True, inplace: bool = False
- ) -> None:
- """
- See NDFrame._maybe_update_cacher.__doc__
- """
- # for CoW, we never want to update the parent DataFrame cache
- # if the Series changed, but don't keep track of any cacher
- if using_copy_on_write():
- return
- cacher = getattr(self, "_cacher", None)
- if cacher is not None:
- ref: DataFrame = cacher[1]()
-
- # we are trying to reference a dead referent, hence
- # a copy
- if ref is None:
- del self._cacher
- elif len(self) == len(ref) and self.name in ref.columns:
- # GH#42530 self.name must be in ref.columns
- # to ensure column still in dataframe
- # otherwise, either self or ref has swapped in new arrays
- ref._maybe_cache_changed(cacher[0], self, inplace=inplace)
- else:
- # GH#33675 we have swapped in a new array, so parent
- # reference to self is now invalid
- ref._item_cache.pop(cacher[0], None)
-
- super()._maybe_update_cacher(
- clear=clear, verify_is_copy=verify_is_copy, inplace=inplace
- )
-
# ----------------------------------------------------------------------
# Unsorted
@@ -3578,7 +3494,6 @@ def update(self, other: Series | Sequence | Mapping) -> None:
mask = notna(other)
self._mgr = self._mgr.putmask(mask=mask, new=other)
- self._maybe_update_cacher()
# ----------------------------------------------------------------------
# Reindexing, sorting
@@ -3782,13 +3697,6 @@ def sort_values(
# Validate the axis parameter
self._get_axis_number(axis)
- # GH 5856/5853
- if inplace and self._is_cached:
- raise ValueError(
- "This Series is a view of some other array, to "
- "sort in-place you must create a copy"
- )
-
if is_list_like(ascending):
ascending = cast(Sequence[bool], ascending)
if len(ascending) != 1:
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index 52b896dc01e8f..97db508bda1b4 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -408,50 +408,6 @@ class SpecificationError(Exception):
"""
-class SettingWithCopyError(ValueError):
- """
- Exception raised when trying to set on a copied slice from a ``DataFrame``.
-
- The ``mode.chained_assignment`` needs to be set to set to 'raise.' This can
- happen unintentionally when chained indexing.
-
- For more information on evaluation order,
- see :ref:`the user guide<indexing.evaluation_order>`.
-
- For more information on view vs. copy,
- see :ref:`the user guide<indexing.view_versus_copy>`.
-
- Examples
- --------
- >>> pd.options.mode.chained_assignment = 'raise'
- >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
- >>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
- ... # SettingWithCopyError: A value is trying to be set on a copy of a...
- """
-
-
-class SettingWithCopyWarning(Warning):
- """
- Warning raised when trying to set on a copied slice from a ``DataFrame``.
-
- The ``mode.chained_assignment`` needs to be set to set to 'warn.'
- 'Warn' is the default option. This can happen unintentionally when
- chained indexing.
-
- For more information on evaluation order,
- see :ref:`the user guide<indexing.evaluation_order>`.
-
- For more information on view vs. copy,
- see :ref:`the user guide<indexing.view_versus_copy>`.
-
- Examples
- --------
- >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
- >>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
- ... # SettingWithCopyWarning: A value is trying to be set on a copy of a...
- """
-
-
class ChainedAssignmentError(Warning):
"""
Warning raised when trying to set using chained assignment.
@@ -462,8 +418,8 @@ class ChainedAssignmentError(Warning):
Copy-on-Write always behaves as a copy. Thus, assigning through a chain
can never update the original Series or DataFrame.
- For more information on view vs. copy,
- see :ref:`the user guide<indexing.view_versus_copy>`.
+ For more information on Copy-on-Write,
+ see :ref:`the user guide<copy_on_write>`.
Examples
--------
@@ -787,8 +743,6 @@ class InvalidComparison(Exception):
"PossiblePrecisionLoss",
"PyperclipException",
"PyperclipWindowsException",
- "SettingWithCopyError",
- "SettingWithCopyWarning",
"SpecificationError",
"UndefinedVariableError",
"UnsortedIndexError",
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 594fb8651f8f0..cea34cdfb0b9d 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -251,8 +251,6 @@ def __init__(
self.default_handler = default_handler
self.index = index
self.indent = indent
-
- self.is_copy = None
self._format_axes()
def _format_axes(self) -> None:
diff --git a/pandas/tests/copy_view/test_chained_assignment_deprecation.py b/pandas/tests/copy_view/test_chained_assignment_deprecation.py
index cfa9cf64357b6..e1a76e66c107f 100644
--- a/pandas/tests/copy_view/test_chained_assignment_deprecation.py
+++ b/pandas/tests/copy_view/test_chained_assignment_deprecation.py
@@ -1,15 +1,9 @@
import numpy as np
import pytest
-from pandas.errors import (
- ChainedAssignmentError,
- SettingWithCopyWarning,
-)
+from pandas.errors import ChainedAssignmentError
-from pandas import (
- DataFrame,
- option_context,
-)
+from pandas import DataFrame
import pandas._testing as tm
@@ -53,15 +47,11 @@ def test_series_setitem(indexer, using_copy_on_write):
assert "ChainedAssignmentError" in record[0].message.args[0]
-@pytest.mark.filterwarnings("ignore::pandas.errors.SettingWithCopyWarning")
@pytest.mark.parametrize(
"indexer", ["a", ["a", "b"], slice(0, 2), np.array([True, False, True])]
)
-def test_frame_setitem(indexer, using_copy_on_write):
+def test_frame_setitem(indexer):
df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
- extra_warnings = () if using_copy_on_write else (SettingWithCopyWarning,)
-
- with option_context("chained_assignment", "warn"):
- with tm.raises_chained_assignment_error(extra_warnings=extra_warnings):
- df[0:3][indexer] = 10
+ with tm.raises_chained_assignment_error():
+ df[0:3][indexer] = 10
diff --git a/pandas/tests/copy_view/test_clip.py b/pandas/tests/copy_view/test_clip.py
index 9be9ba6f144c4..c18a2e1e65d26 100644
--- a/pandas/tests/copy_view/test_clip.py
+++ b/pandas/tests/copy_view/test_clip.py
@@ -1,9 +1,6 @@
import numpy as np
-from pandas import (
- DataFrame,
- option_context,
-)
+from pandas import DataFrame
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
@@ -89,9 +86,7 @@ def test_clip_chained_inplace(using_copy_on_write):
df["a"].clip(1, 2, inplace=True)
with tm.assert_produces_warning(None):
- with option_context("mode.chained_assignment", None):
- df[["a"]].clip(1, 2, inplace=True)
+ df[["a"]].clip(1, 2, inplace=True)
with tm.assert_produces_warning(None):
- with option_context("mode.chained_assignment", None):
- df[df["a"] > 1].clip(1, 2, inplace=True)
+ df[df["a"] > 1].clip(1, 2, inplace=True)
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py
index 69fb8fe2c6f63..da72e89b23ca0 100644
--- a/pandas/tests/copy_view/test_indexing.py
+++ b/pandas/tests/copy_view/test_indexing.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-from pandas.errors import SettingWithCopyWarning
-
from pandas.core.dtypes.common import is_float_dtype
import pandas as pd
@@ -59,17 +57,10 @@ def test_subset_column_selection(backend, using_copy_on_write):
subset = df[["a", "c"]]
- if using_copy_on_write:
- # the subset shares memory ...
- assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
- # ... but uses CoW when being modified
- subset.iloc[0, 0] = 0
- else:
- assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
- # INFO this no longer raise warning since pandas 1.4
- # with pd.option_context("chained_assignment", "warn"):
- # with tm.assert_produces_warning(SettingWithCopyWarning):
- subset.iloc[0, 0] = 0
+ # the subset shares memory ...
+ assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
+ # ... but uses CoW when being modified
+ subset.iloc[0, 0] = 0
assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
@@ -113,37 +104,24 @@ def test_subset_row_slice(backend, using_copy_on_write):
assert np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
- if using_copy_on_write:
- subset.iloc[0, 0] = 0
- assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
-
- else:
- # INFO this no longer raise warning since pandas 1.4
- # with pd.option_context("chained_assignment", "warn"):
- # with tm.assert_produces_warning(SettingWithCopyWarning):
- subset.iloc[0, 0] = 0
+ subset.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
subset._mgr._verify_integrity()
expected = DataFrame({"a": [0, 3], "b": [5, 6], "c": [0.2, 0.3]}, index=range(1, 3))
tm.assert_frame_equal(subset, expected)
- if using_copy_on_write:
- # original parent dataframe is not modified (CoW)
- tm.assert_frame_equal(df, df_orig)
- else:
- # original parent dataframe is actually updated
- df_orig.iloc[1, 0] = 0
- tm.assert_frame_equal(df, df_orig)
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
@pytest.mark.parametrize(
"dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
)
-def test_subset_column_slice(backend, using_copy_on_write, dtype):
+def test_subset_column_slice(backend, dtype):
# Case: taking a subset of the columns of a DataFrame using a slice
# + afterwards modifying the subset
dtype_backend, DataFrame, _ = backend
- single_block = dtype == "int64" and dtype_backend == "numpy"
df = DataFrame(
{"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}
)
@@ -152,27 +130,16 @@ def test_subset_column_slice(backend, using_copy_on_write, dtype):
subset = df.iloc[:, 1:]
subset._mgr._verify_integrity()
- if using_copy_on_write:
- assert np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
- subset.iloc[0, 0] = 0
- assert not np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
- else:
- # we only get a warning in case of a single block
- warn = SettingWithCopyWarning if single_block else None
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- subset.iloc[0, 0] = 0
+ subset.iloc[0, 0] = 0
+ assert not np.shares_memory(get_array(subset, "b"), get_array(df, "b"))
expected = DataFrame({"b": [0, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)})
tm.assert_frame_equal(subset, expected)
# original parent dataframe is not modified (also not for BlockManager case,
# except for single block)
- if not using_copy_on_write and single_block:
- df_orig.iloc[0, 1] = 0
- tm.assert_frame_equal(df, df_orig)
- else:
- tm.assert_frame_equal(df, df_orig)
+ tm.assert_frame_equal(df, df_orig)
@pytest.mark.parametrize(
@@ -288,7 +255,7 @@ def test_subset_iloc_rows_columns(
[slice(0, 2), np.array([True, True, False]), np.array([0, 1])],
ids=["slice", "mask", "array"],
)
-def test_subset_set_with_row_indexer(backend, indexer_si, indexer, using_copy_on_write):
+def test_subset_set_with_row_indexer(backend, indexer_si, indexer):
# Case: setting values with a row indexer on a viewing subset
# subset[indexer] = value and subset.iloc[indexer] = value
_, DataFrame, _ = backend
@@ -303,29 +270,17 @@ def test_subset_set_with_row_indexer(backend, indexer_si, indexer, using_copy_on
):
pytest.skip("setitem with labels selects on columns")
- if using_copy_on_write:
- indexer_si(subset)[indexer] = 0
- else:
- # INFO iloc no longer raises warning since pandas 1.4
- warn = SettingWithCopyWarning if indexer_si is tm.setitem else None
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- indexer_si(subset)[indexer] = 0
+ indexer_si(subset)[indexer] = 0
expected = DataFrame(
{"a": [0, 0, 4], "b": [0, 0, 7], "c": [0.0, 0.0, 0.4]}, index=range(1, 4)
)
tm.assert_frame_equal(subset, expected)
- if using_copy_on_write:
- # original parent dataframe is not modified (CoW)
- tm.assert_frame_equal(df, df_orig)
- else:
- # original parent dataframe is actually updated
- df_orig[1:3] = 0
- tm.assert_frame_equal(df, df_orig)
+ # original parent dataframe is not modified (CoW)
+ tm.assert_frame_equal(df, df_orig)
-def test_subset_set_with_mask(backend, using_copy_on_write):
+def test_subset_set_with_mask(backend):
# Case: setting values with a mask on a viewing subset: subset[mask] = value
_, DataFrame, _ = backend
df = DataFrame({"a": [1, 2, 3, 4], "b": [4, 5, 6, 7], "c": [0.1, 0.2, 0.3, 0.4]})
@@ -334,28 +289,16 @@ def test_subset_set_with_mask(backend, using_copy_on_write):
mask = subset > 3
- if using_copy_on_write:
- subset[mask] = 0
- else:
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- subset[mask] = 0
+ subset[mask] = 0
expected = DataFrame(
{"a": [2, 3, 0], "b": [0, 0, 0], "c": [0.20, 0.3, 0.4]}, index=range(1, 4)
)
tm.assert_frame_equal(subset, expected)
- if using_copy_on_write:
- # original parent dataframe is not modified (CoW)
- tm.assert_frame_equal(df, df_orig)
- else:
- # original parent dataframe is actually updated
- df_orig.loc[3, "a"] = 0
- df_orig.loc[1:3, "b"] = 0
- tm.assert_frame_equal(df, df_orig)
+ tm.assert_frame_equal(df, df_orig)
-def test_subset_set_column(backend, using_copy_on_write):
+def test_subset_set_column(backend):
# Case: setting a single column on a viewing subset -> subset[col] = value
dtype_backend, DataFrame, _ = backend
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
@@ -367,13 +310,7 @@ def test_subset_set_column(backend, using_copy_on_write):
else:
arr = pd.array([10, 11], dtype="Int64")
- if using_copy_on_write:
- subset["a"] = arr
- else:
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- subset["a"] = arr
-
+ subset["a"] = arr
subset._mgr._verify_integrity()
expected = DataFrame(
{"a": [10, 11], "b": [5, 6], "c": [0.2, 0.3]}, index=range(1, 3)
@@ -459,17 +396,11 @@ def test_subset_set_columns(backend, using_copy_on_write, dtype):
df_orig = df.copy()
subset = df[1:3]
- if using_copy_on_write:
- subset[["a", "c"]] = 0
- else:
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- subset[["a", "c"]] = 0
+ subset[["a", "c"]] = 0
subset._mgr._verify_integrity()
- if using_copy_on_write:
- # first and third column should certainly have no references anymore
- assert all(subset._mgr._has_no_reference(i) for i in [0, 2])
+ # first and third column should certainly have no references anymore
+ assert all(subset._mgr._has_no_reference(i) for i in [0, 2])
expected = DataFrame({"a": [0, 0], "b": [5, 6], "c": [0, 0]}, index=range(1, 3))
if dtype_backend == "nullable":
# there is not yet a global option, so overriding a column by setting a scalar
@@ -582,7 +513,7 @@ def test_subset_chained_getitem(
@pytest.mark.parametrize(
"dtype", ["int64", "float64"], ids=["single-block", "mixed-block"]
)
-def test_subset_chained_getitem_column(backend, dtype, using_copy_on_write):
+def test_subset_chained_getitem_column(backend, dtype):
# Case: creating a subset using multiple, chained getitem calls using views
# still needs to guarantee proper CoW behaviour
dtype_backend, DataFrame, Series = backend
@@ -593,22 +524,14 @@ def test_subset_chained_getitem_column(backend, dtype, using_copy_on_write):
# modify subset -> don't modify parent
subset = df[:]["a"][0:2]
- df._clear_item_cache()
subset.iloc[0] = 0
- if using_copy_on_write:
- tm.assert_frame_equal(df, df_orig)
- else:
- assert df.iloc[0, 0] == 0
+ tm.assert_frame_equal(df, df_orig)
# modify parent -> don't modify subset
subset = df[:]["a"][0:2]
- df._clear_item_cache()
df.iloc[0, 0] = 0
expected = Series([1, 2], name="a")
- if using_copy_on_write:
- tm.assert_series_equal(subset, expected)
- else:
- assert subset.iloc[0] == 0
+ tm.assert_series_equal(subset, expected)
@pytest.mark.parametrize(
@@ -877,7 +800,7 @@ def test_del_series(backend):
# Accessing column as Series
-def test_column_as_series(backend, using_copy_on_write):
+def test_column_as_series(backend):
# Case: selecting a single column now also uses Copy-on-Write
dtype_backend, DataFrame, Series = backend
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
@@ -886,28 +809,17 @@ def test_column_as_series(backend, using_copy_on_write):
s = df["a"]
assert np.shares_memory(get_array(s, "a"), get_array(df, "a"))
-
- if using_copy_on_write:
- s[0] = 0
- else:
- warn = SettingWithCopyWarning if dtype_backend == "numpy" else None
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- s[0] = 0
+ s[0] = 0
expected = Series([0, 2, 3], name="a")
tm.assert_series_equal(s, expected)
- if using_copy_on_write:
- # assert not np.shares_memory(s.values, get_array(df, "a"))
- tm.assert_frame_equal(df, df_orig)
- # ensure cached series on getitem is not the changed series
- tm.assert_series_equal(df["a"], df_orig["a"])
- else:
- df_orig.iloc[0, 0] = 0
- tm.assert_frame_equal(df, df_orig)
+ # assert not np.shares_memory(s.values, get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
+ # ensure cached series on getitem is not the changed series
+ tm.assert_series_equal(df["a"], df_orig["a"])
-def test_column_as_series_set_with_upcast(backend, using_copy_on_write):
+def test_column_as_series_set_with_upcast(backend):
# Case: selecting a single column now also uses Copy-on-Write -> when
# setting a value causes an upcast, we don't need to update the parent
# DataFrame through the cache mechanism
@@ -920,32 +832,15 @@ def test_column_as_series_set_with_upcast(backend, using_copy_on_write):
with pytest.raises(TypeError, match="Invalid value"):
s[0] = "foo"
expected = Series([1, 2, 3], name="a")
- elif using_copy_on_write:
+ else:
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
s[0] = "foo"
expected = Series(["foo", 2, 3], dtype=object, name="a")
- else:
- with pd.option_context("chained_assignment", "warn"):
- msg = "|".join(
- [
- "A value is trying to be set on a copy of a slice from a DataFrame",
- "Setting an item of incompatible dtype is deprecated",
- ]
- )
- with tm.assert_produces_warning(
- (SettingWithCopyWarning, FutureWarning), match=msg
- ):
- s[0] = "foo"
- expected = Series(["foo", 2, 3], dtype=object, name="a")
tm.assert_series_equal(s, expected)
- if using_copy_on_write:
- tm.assert_frame_equal(df, df_orig)
- # ensure cached series on getitem is not the changed series
- tm.assert_series_equal(df["a"], df_orig["a"])
- else:
- df_orig["a"] = expected
- tm.assert_frame_equal(df, df_orig)
+ tm.assert_frame_equal(df, df_orig)
+ # ensure cached series on getitem is not the changed series
+ tm.assert_series_equal(df["a"], df_orig["a"])
@pytest.mark.parametrize(
@@ -957,12 +852,7 @@ def test_column_as_series_set_with_upcast(backend, using_copy_on_write):
],
ids=["getitem", "loc", "iloc"],
)
-def test_column_as_series_no_item_cache(
- request,
- backend,
- method,
- using_copy_on_write,
-):
+def test_column_as_series_no_item_cache(request, backend, method):
# Case: selecting a single column (which now also uses Copy-on-Write to protect
# the view) should always give a new object (i.e. not make use of a cache)
dtype_backend, DataFrame, _ = backend
@@ -972,25 +862,12 @@ def test_column_as_series_no_item_cache(
s1 = method(df)
s2 = method(df)
- is_iloc = "iloc" in request.node.name
- if using_copy_on_write or is_iloc:
- assert s1 is not s2
- else:
- assert s1 is s2
+ assert s1 is not s2
- if using_copy_on_write:
- s1.iloc[0] = 0
- else:
- warn = SettingWithCopyWarning if dtype_backend == "numpy" else None
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- s1.iloc[0] = 0
+ s1.iloc[0] = 0
- if using_copy_on_write:
- tm.assert_series_equal(s2, df_orig["a"])
- tm.assert_frame_equal(df, df_orig)
- else:
- assert s2.iloc[0] == 0
+ tm.assert_series_equal(s2, df_orig["a"])
+ tm.assert_frame_equal(df, df_orig)
# TODO add tests for other indexing methods on the Series
@@ -1074,23 +951,16 @@ def test_series_midx_slice(using_copy_on_write):
tm.assert_series_equal(ser, expected)
-def test_getitem_midx_slice(using_copy_on_write):
+def test_getitem_midx_slice():
df = DataFrame({("a", "x"): [1, 2], ("a", "y"): 1, ("b", "x"): 2})
df_orig = df.copy()
new_df = df[("a",)]
- if using_copy_on_write:
- assert not new_df._mgr._has_no_reference(0)
+ assert not new_df._mgr._has_no_reference(0)
assert np.shares_memory(get_array(df, ("a", "x")), get_array(new_df, "x"))
- if using_copy_on_write:
- new_df.iloc[0, 0] = 100
- tm.assert_frame_equal(df_orig, df)
- else:
- with pd.option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- new_df.iloc[0, 0] = 100
- assert df.iloc[0, 0] == 100
+ new_df.iloc[0, 0] = 100
+ tm.assert_frame_equal(df_orig, df)
def test_series_midx_tuples_slice(using_copy_on_write):
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index b3bd63e1c7e4c..011d18f8e609f 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-from pandas.errors import SettingWithCopyWarning
-
import pandas as pd
from pandas import (
DataFrame,
@@ -12,7 +10,6 @@
Series,
Timestamp,
date_range,
- option_context,
period_range,
)
import pandas._testing as tm
@@ -1540,12 +1537,10 @@ def test_chained_where_mask(using_copy_on_write, func):
getattr(df["a"], func)(df["a"] > 2, 5, inplace=True)
with tm.assert_produces_warning(None):
- with option_context("mode.chained_assignment", None):
- getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True)
+ getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True)
with tm.assert_produces_warning(None):
- with option_context("mode.chained_assignment", None):
- getattr(df[df["a"] > 1], func)(df["a"] > 2, 5, inplace=True)
+ getattr(df[df["a"] > 1], func)(df["a"] > 2, 5, inplace=True)
def test_asfreq_noop(using_copy_on_write):
@@ -1667,23 +1662,10 @@ def test_get(using_copy_on_write, key):
result = df.get(key)
- if using_copy_on_write:
- assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
- result.iloc[0] = 0
- assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
- tm.assert_frame_equal(df, df_orig)
- else:
- # for non-CoW it depends on whether we got a Series or DataFrame if it
- # is a view or copy or triggers a warning or not
- warn = SettingWithCopyWarning if isinstance(key, list) else None
- with option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- result.iloc[0] = 0
-
- if isinstance(key, list):
- tm.assert_frame_equal(df, df_orig)
- else:
- assert df.iloc[0, 0] == 0
+ assert np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ result.iloc[0] = 0
+ assert not np.shares_memory(get_array(result, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(df, df_orig)
@pytest.mark.parametrize("axis, key", [(0, 0), (1, "a")])
@@ -1701,20 +1683,13 @@ def test_xs(using_copy_on_write, axis, key, dtype):
if axis == 1 or single_block:
assert np.shares_memory(get_array(df, "a"), get_array(result))
- elif using_copy_on_write:
+ else:
assert result._mgr._has_no_reference(0)
if using_copy_on_write or single_block:
result.iloc[0] = 0
- else:
- with option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- result.iloc[0] = 0
- if using_copy_on_write or (not single_block and axis == 0):
- tm.assert_frame_equal(df, df_orig)
- else:
- assert df.iloc[0, 0] == 0
+ tm.assert_frame_equal(df, df_orig)
@pytest.mark.parametrize("axis", [0, 1])
@@ -1733,14 +1708,7 @@ def test_xs_multiindex(using_copy_on_write, key, level, axis):
assert np.shares_memory(
get_array(df, df.columns[0]), get_array(result, result.columns[0])
)
-
- if not using_copy_on_write:
- warn = SettingWithCopyWarning
- else:
- warn = None
- with option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(warn):
- result.iloc[0, 0] = 0
+ result.iloc[0, 0] = 0
tm.assert_frame_equal(df, df_orig)
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index c8787ac0b364e..b48ad7e3481b9 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -13,7 +13,6 @@
from pandas.errors import (
InvalidIndexError,
PerformanceWarning,
- SettingWithCopyError,
)
from pandas.core.dtypes.common import is_integer
@@ -287,7 +286,7 @@ def test_setattr_column(self):
df.foobar = 5
assert (df.foobar == 5).all()
- def test_setitem(self, float_frame, using_copy_on_write, using_infer_string):
+ def test_setitem(self, float_frame, using_infer_string):
# not sure what else to do here
series = float_frame["A"][::2]
float_frame["col5"] = series
@@ -322,13 +321,8 @@ def test_setitem(self, float_frame, using_copy_on_write, using_infer_string):
# so raise/warn
smaller = float_frame[:2]
- msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"
- if using_copy_on_write:
- # With CoW, adding a new column doesn't raise a warning
- smaller["col10"] = ["1", "2"]
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- smaller["col10"] = ["1", "2"]
+ # With CoW, adding a new column doesn't raise a warning
+ smaller["col10"] = ["1", "2"]
if using_infer_string:
assert smaller["col10"].dtype == "string"
diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py
index dc2f0b61e3ba0..96ae1050ed15a 100644
--- a/pandas/tests/frame/indexing/test_xs.py
+++ b/pandas/tests/frame/indexing/test_xs.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-from pandas.errors import SettingWithCopyError
-
from pandas import (
DataFrame,
Index,
@@ -122,21 +120,16 @@ def test_xs_keep_level(self):
result = df.xs((2008, "sat"), level=["year", "day"], drop_level=False)
tm.assert_frame_equal(result, expected)
- def test_xs_view(self, using_copy_on_write):
+ def test_xs_view(self):
# in 0.14 this will return a view if possible a copy otherwise, but
# this is numpy dependent
dm = DataFrame(np.arange(20.0).reshape(4, 5), index=range(4), columns=range(5))
df_orig = dm.copy()
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- dm.xs(2)[:] = 20
- tm.assert_frame_equal(dm, df_orig)
- else:
- with tm.raises_chained_assignment_error():
- dm.xs(2)[:] = 20
- assert (dm.xs(2) == 20).all()
+ with tm.raises_chained_assignment_error():
+ dm.xs(2)[:] = 20
+ tm.assert_frame_equal(dm, df_orig)
class TestXSWithMultiIndex:
@@ -194,42 +187,22 @@ def test_xs_level_eq_2(self):
result = df.xs("c", level=2)
tm.assert_frame_equal(result, expected)
- def test_xs_setting_with_copy_error(
- self,
- multiindex_dataframe_random_data,
- using_copy_on_write,
- ):
+ def test_xs_setting_with_copy_error(self, multiindex_dataframe_random_data):
# this is a copy in 0.14
df = multiindex_dataframe_random_data
df_orig = df.copy()
result = df.xs("two", level="second")
- if using_copy_on_write:
- result[:] = 10
- else:
- # setting this will give a SettingWithCopyError
- # as we are trying to write a view
- msg = "A value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- result[:] = 10
+ result[:] = 10
tm.assert_frame_equal(df, df_orig)
- def test_xs_setting_with_copy_error_multiple(
- self, four_level_index_dataframe, using_copy_on_write
- ):
+ def test_xs_setting_with_copy_error_multiple(self, four_level_index_dataframe):
# this is a copy in 0.14
df = four_level_index_dataframe
df_orig = df.copy()
result = df.xs(("a", 4), level=["one", "four"])
- if using_copy_on_write:
- result[:] = 10
- else:
- # setting this will give a SettingWithCopyError
- # as we are trying to write a view
- msg = "A value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- result[:] = 10
+ result[:] = 10
tm.assert_frame_equal(df, df_orig)
@pytest.mark.parametrize("key, level", [("one", "second"), (["one"], ["second"])])
diff --git a/pandas/tests/frame/methods/test_asof.py b/pandas/tests/frame/methods/test_asof.py
index 4a8adf89b3aef..029aa3a5b8f05 100644
--- a/pandas/tests/frame/methods/test_asof.py
+++ b/pandas/tests/frame/methods/test_asof.py
@@ -163,19 +163,6 @@ def test_time_zone_aware_index(self, stamp, expected):
result = df.asof(stamp)
tm.assert_series_equal(result, expected)
- def test_is_copy(self, date_range_frame):
- # GH-27357, GH-30784: ensure the result of asof is an actual copy and
- # doesn't track the parent dataframe / doesn't give SettingWithCopy warnings
- df = date_range_frame.astype({"A": "float"})
- N = 50
- df.loc[df.index[15:30], "A"] = np.nan
- dates = date_range("1/1/1990", periods=N * 3, freq="25s")
-
- result = df.asof(dates)
-
- with tm.assert_produces_warning(None):
- result["C"] = 1
-
def test_asof_periodindex_mismatched_freq(self):
N = 50
rng = period_range("1/1/1990", periods=N, freq="h")
diff --git a/pandas/tests/frame/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py
index e65225a33a479..91d735a8b2fa7 100644
--- a/pandas/tests/frame/methods/test_sample.py
+++ b/pandas/tests/frame/methods/test_sample.py
@@ -333,7 +333,7 @@ def test_sample_aligns_weights_with_frame(self):
def test_sample_is_copy(self):
# GH#27357, GH#30784: ensure the result of sample is an actual copy and
- # doesn't track the parent dataframe / doesn't give SettingWithCopy warnings
+ # doesn't track the parent dataframe
df = DataFrame(
np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]
)
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index b33ca95bd4180..768c85644c977 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -331,21 +331,15 @@ def test_sort_values_datetimes(self):
df2 = df.sort_values(by=["C", "B"])
tm.assert_frame_equal(df1, df2)
- def test_sort_values_frame_column_inplace_sort_exception(
- self, float_frame, using_copy_on_write
- ):
+ def test_sort_values_frame_column_inplace_sort_exception(self, float_frame):
s = float_frame["A"]
float_frame_orig = float_frame.copy()
- if using_copy_on_write:
- # INFO(CoW) Series is a new object, so can be changed inplace
- # without modifying original datafame
- s.sort_values(inplace=True)
- tm.assert_series_equal(s, float_frame_orig["A"].sort_values())
- # column in dataframe is not changed
- tm.assert_frame_equal(float_frame, float_frame_orig)
- else:
- with pytest.raises(ValueError, match="This Series is a view"):
- s.sort_values(inplace=True)
+ # INFO(CoW) Series is a new object, so can be changed inplace
+ # without modifying original datafame
+ s.sort_values(inplace=True)
+ tm.assert_series_equal(s, float_frame_orig["A"].sort_values())
+ # column in dataframe is not changed
+ tm.assert_frame_equal(float_frame, float_frame_orig)
cp = s.copy()
cp.sort_values() # it works!
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 67bebddaa63ca..0bfde350c259b 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -577,10 +577,9 @@ def f(group):
assert result["d"].dtype == np.float64
# this is by definition a mutating operation!
- with pd.option_context("mode.chained_assignment", None):
- for key, group in grouped:
- res = f(group)
- tm.assert_frame_equal(res, result.loc[key])
+ for key, group in grouped:
+ res = f(group)
+ tm.assert_frame_equal(res, result.loc[key])
@pytest.mark.parametrize(
diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py
index 6eeaeb6711d03..dd4bba42eda6f 100644
--- a/pandas/tests/indexes/multi/test_get_set.py
+++ b/pandas/tests/indexes/multi/test_get_set.py
@@ -332,10 +332,8 @@ def test_set_value_keeps_names():
index=idx,
)
df = df.sort_index()
- assert df._is_copy is None
assert df.index.names == ("Name", "Number")
df.at[("grethe", "4"), "one"] = 99.34
- assert df._is_copy is None
assert df.index.names == ("Name", "Number")
diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
index 24a111e283365..c70c0ee10afd6 100644
--- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
@@ -1,8 +1,6 @@
import numpy as np
-import pytest
from pandas._libs import index as libindex
-from pandas.errors import SettingWithCopyError
from pandas import (
DataFrame,
@@ -12,7 +10,7 @@
import pandas._testing as tm
-def test_detect_chained_assignment(using_copy_on_write):
+def test_detect_chained_assignment():
# Inplace ops, originally from:
# https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
a = [12, 23]
@@ -29,14 +27,8 @@ def test_detect_chained_assignment(using_copy_on_write):
multiind = MultiIndex.from_tuples(tuples, names=["part", "side"])
zed = DataFrame(events, index=["a", "b"], columns=multiind)
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- zed["eyes"]["right"].fillna(value=555, inplace=True)
- else:
- msg = "A value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.assert_produces_warning(None):
- zed["eyes"]["right"].fillna(value=555, inplace=True)
+ with tm.raises_chained_assignment_error():
+ zed["eyes"]["right"].fillna(value=555, inplace=True)
def test_cache_updating(using_copy_on_write):
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index 17b00244c70f5..d731f796637ea 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-from pandas.errors import SettingWithCopyError
-
import pandas as pd
from pandas import (
DataFrame,
@@ -522,38 +520,21 @@ def test_frame_setitem_view_direct(
assert (df["foo"].values == 0).all()
-def test_frame_setitem_copy_raises(
- multiindex_dataframe_random_data, using_copy_on_write
-):
+def test_frame_setitem_copy_raises(multiindex_dataframe_random_data):
# will raise/warn as its chained assignment
df = multiindex_dataframe_random_data.T
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df["foo"]["one"] = 2
- else:
- msg = "A value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["foo"]["one"] = 2
+ with tm.raises_chained_assignment_error():
+ df["foo"]["one"] = 2
-def test_frame_setitem_copy_no_write(
- multiindex_dataframe_random_data, using_copy_on_write
-):
+def test_frame_setitem_copy_no_write(multiindex_dataframe_random_data):
frame = multiindex_dataframe_random_data.T
expected = frame
df = frame.copy()
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df["foo"]["one"] = 2
- else:
- msg = "A value is trying to be set on a copy of a slice from a DataFrame"
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["foo"]["one"] = 2
+ with tm.raises_chained_assignment_error():
+ df["foo"]["one"] = 2
- result = df
- tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(df, expected)
def test_frame_setitem_partial_multiindex():
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index 6dbe4f2b3ed3a..7945d88c4a7dc 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -3,11 +3,6 @@
import numpy as np
import pytest
-from pandas.errors import (
- SettingWithCopyError,
- SettingWithCopyWarning,
-)
-
import pandas as pd
from pandas import (
DataFrame,
@@ -47,11 +42,7 @@ def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write):
# Assignment to wrong series
with tm.raises_chained_assignment_error():
df["bb"].iloc[0] = 0.17
- df._clear_item_cache()
- if not using_copy_on_write:
- tm.assert_almost_equal(df["bb"][0], 0.17)
- else:
- tm.assert_almost_equal(df["bb"][0], 2.2)
+ tm.assert_almost_equal(df["bb"][0], 2.2)
@pytest.mark.parametrize("do_ref", [True, False])
def test_setitem_cache_updating(self, do_ref):
@@ -116,16 +107,10 @@ def test_altering_series_clears_parent_cache(self, using_copy_on_write):
df = DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])
ser = df["A"]
- if using_copy_on_write:
- assert "A" not in df._item_cache
- else:
- assert "A" in df._item_cache
-
# Adding a new entry to ser swaps in a new array, so "A" needs to
# be removed from df._item_cache
ser["c"] = 5
assert len(ser) == 3
- assert "A" not in df._item_cache
assert df["A"] is not ser
assert len(df["A"]) == 2
@@ -192,7 +177,6 @@ def test_detect_chained_assignment(self, using_copy_on_write):
np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64"
)
df_original = df.copy()
- assert df._is_copy is None
with tm.raises_chained_assignment_error():
df["A"][0] = -5
@@ -204,7 +188,7 @@ def test_detect_chained_assignment(self, using_copy_on_write):
tm.assert_frame_equal(df, expected)
@pytest.mark.arm_slow
- def test_detect_chained_assignment_raises(self, using_copy_on_write):
+ def test_detect_chained_assignment_raises(self):
# test with the chaining
df = DataFrame(
{
@@ -213,27 +197,14 @@ def test_detect_chained_assignment_raises(self, using_copy_on_write):
}
)
df_original = df.copy()
- assert df._is_copy is None
-
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df["A"][0] = -5
- with tm.raises_chained_assignment_error():
- df["A"][1] = -6
- tm.assert_frame_equal(df, df_original)
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["A"][0] = -5
-
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["A"][1] = np.nan
-
- assert df["A"]._is_copy is None
+ with tm.raises_chained_assignment_error():
+ df["A"][0] = -5
+ with tm.raises_chained_assignment_error():
+ df["A"][1] = -6
+ tm.assert_frame_equal(df, df_original)
@pytest.mark.arm_slow
- def test_detect_chained_assignment_fails(self, using_copy_on_write):
+ def test_detect_chained_assignment_fails(self):
# Using a copy (the chain), fails
df = DataFrame(
{
@@ -242,15 +213,11 @@ def test_detect_chained_assignment_fails(self, using_copy_on_write):
}
)
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df.loc[0]["A"] = -5
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- df.loc[0]["A"] = -5
+ with tm.raises_chained_assignment_error():
+ df.loc[0]["A"] = -5
@pytest.mark.arm_slow
- def test_detect_chained_assignment_doc_example(self, using_copy_on_write):
+ def test_detect_chained_assignment_doc_example(self):
# Doc example
df = DataFrame(
{
@@ -258,45 +225,26 @@ def test_detect_chained_assignment_doc_example(self, using_copy_on_write):
"c": Series(range(7), dtype="int64"),
}
)
- assert df._is_copy is None
indexer = df.a.str.startswith("o")
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df[indexer]["c"] = 42
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- df[indexer]["c"] = 42
+ with tm.raises_chained_assignment_error():
+ df[indexer]["c"] = 42
@pytest.mark.arm_slow
- def test_detect_chained_assignment_object_dtype(self, using_copy_on_write):
- expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]})
+ def test_detect_chained_assignment_object_dtype(self):
df = DataFrame(
{"A": Series(["aaa", "bbb", "ccc"], dtype=object), "B": [1, 2, 3]}
)
df_original = df.copy()
- if not using_copy_on_write:
- with pytest.raises(SettingWithCopyError, match=msg):
- df.loc[0]["A"] = 111
-
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df["A"][0] = 111
- tm.assert_frame_equal(df, df_original)
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["A"][0] = 111
-
- df.loc[0, "A"] = 111
- tm.assert_frame_equal(df, expected)
+ with tm.raises_chained_assignment_error():
+ df["A"][0] = 111
+ tm.assert_frame_equal(df, df_original)
@pytest.mark.arm_slow
def test_detect_chained_assignment_is_copy_pickle(self):
# gh-5475: Make sure that is_copy is picked up reconstruction
df = DataFrame({"A": [1, 2]})
- assert df._is_copy is None
with tm.ensure_clean("__tmp__pickle") as path:
df.to_pickle(path)
@@ -304,68 +252,12 @@ def test_detect_chained_assignment_is_copy_pickle(self):
df2["B"] = df2["A"]
df2["B"] = df2["A"]
- @pytest.mark.arm_slow
- def test_detect_chained_assignment_setting_entire_column(self):
- # gh-5597: a spurious raise as we are setting the entire column here
-
- df = random_text(100000)
-
- # Always a copy
- x = df.iloc[[0, 1, 2]]
- assert x._is_copy is not None
-
- x = df.iloc[[0, 1, 2, 4]]
- assert x._is_copy is not None
-
- # Explicitly copy
- indexer = df.letters.apply(lambda x: len(x) > 10)
- df = df.loc[indexer].copy()
-
- assert df._is_copy is None
- df["letters"] = df["letters"].apply(str.lower)
-
- @pytest.mark.arm_slow
- def test_detect_chained_assignment_implicit_take(self):
- # Implicitly take
- df = random_text(100000)
- indexer = df.letters.apply(lambda x: len(x) > 10)
- df = df.loc[indexer]
-
- assert df._is_copy is not None
- df["letters"] = df["letters"].apply(str.lower)
-
- @pytest.mark.arm_slow
- def test_detect_chained_assignment_implicit_take2(self, using_copy_on_write):
- if using_copy_on_write:
- pytest.skip("_is_copy is not always set for CoW")
- # Implicitly take 2
- df = random_text(100000)
- indexer = df.letters.apply(lambda x: len(x) > 10)
-
- df = df.loc[indexer]
- assert df._is_copy is not None
- df.loc[:, "letters"] = df["letters"].apply(str.lower)
-
- # with the enforcement of #45333 in 2.0, the .loc[:, letters] setting
- # is inplace, so df._is_copy remains non-None.
- assert df._is_copy is not None
-
- df["letters"] = df["letters"].apply(str.lower)
- assert df._is_copy is None
-
@pytest.mark.arm_slow
def test_detect_chained_assignment_str(self):
df = random_text(100000)
indexer = df.letters.apply(lambda x: len(x) > 10)
df.loc[indexer, "letters"] = df.loc[indexer, "letters"].apply(str.lower)
- @pytest.mark.arm_slow
- def test_detect_chained_assignment_is_copy(self):
- # an identical take, so no copy
- df = DataFrame({"a": [1]}).dropna()
- assert df._is_copy is None
- df["a"] += 1
-
@pytest.mark.arm_slow
def test_detect_chained_assignment_sorting(self):
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
@@ -390,24 +282,18 @@ def test_detect_chained_assignment_false_positives(self):
str(df)
@pytest.mark.arm_slow
- def test_detect_chained_assignment_undefined_column(self, using_copy_on_write):
+ def test_detect_chained_assignment_undefined_column(self):
# from SO:
# https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc
df = DataFrame(np.arange(0, 9), columns=["count"])
df["group"] = "b"
df_original = df.copy()
-
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df.iloc[0:5]["group"] = "a"
- tm.assert_frame_equal(df, df_original)
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df.iloc[0:5]["group"] = "a"
+ with tm.raises_chained_assignment_error():
+ df.iloc[0:5]["group"] = "a"
+ tm.assert_frame_equal(df, df_original)
@pytest.mark.arm_slow
- def test_detect_chained_assignment_changing_dtype(self, using_copy_on_write):
+ def test_detect_chained_assignment_changing_dtype(self):
# Mixed type setting but same dtype & changing dtype
df = DataFrame(
{
@@ -419,44 +305,25 @@ def test_detect_chained_assignment_changing_dtype(self, using_copy_on_write):
)
df_original = df.copy()
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df.loc[2]["D"] = "foo"
- with tm.raises_chained_assignment_error():
- df.loc[2]["C"] = "foo"
- tm.assert_frame_equal(df, df_original)
- with tm.raises_chained_assignment_error(extra_warnings=(FutureWarning,)):
- df["C"][2] = "foo"
- if using_copy_on_write:
- tm.assert_frame_equal(df, df_original)
- else:
- assert df.loc[2, "C"] == "foo"
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- df.loc[2]["D"] = "foo"
-
- with pytest.raises(SettingWithCopyError, match=msg):
- df.loc[2]["C"] = "foo"
-
- with pytest.raises(SettingWithCopyError, match=msg):
- with tm.raises_chained_assignment_error():
- df["C"][2] = "foo"
+ with tm.raises_chained_assignment_error():
+ df.loc[2]["D"] = "foo"
+ with tm.raises_chained_assignment_error():
+ df.loc[2]["C"] = "foo"
+ tm.assert_frame_equal(df, df_original)
+ with tm.raises_chained_assignment_error(extra_warnings=(FutureWarning,)):
+ df["C"][2] = "foo"
+ tm.assert_frame_equal(df, df_original)
- def test_setting_with_copy_bug(self, using_copy_on_write):
+ def test_setting_with_copy_bug(self):
# operating on a copy
df = DataFrame(
{"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]}
)
df_original = df.copy()
mask = pd.isna(df.c)
-
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df[["c"]][mask] = df[["b"]][mask]
- tm.assert_frame_equal(df, df_original)
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- df[["c"]][mask] = df[["b"]][mask]
+ with tm.raises_chained_assignment_error():
+ df[["c"]][mask] = df[["b"]][mask]
+ tm.assert_frame_equal(df, df_original)
def test_setting_with_copy_bug_no_warning(self):
# invalid warning as we are returning a new object
@@ -467,20 +334,10 @@ def test_setting_with_copy_bug_no_warning(self):
# this should not raise
df2["y"] = ["g", "h", "i"]
- def test_detect_chained_assignment_warnings_errors(self, using_copy_on_write):
+ def test_detect_chained_assignment_warnings_errors(self):
df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- df.loc[0]["A"] = 111
- return
-
- with option_context("chained_assignment", "warn"):
- with tm.assert_produces_warning(SettingWithCopyWarning):
- df.loc[0]["A"] = 111
-
- with option_context("chained_assignment", "raise"):
- with pytest.raises(SettingWithCopyError, match=msg):
- df.loc[0]["A"] = 111
+ with tm.raises_chained_assignment_error():
+ df.loc[0]["A"] = 111
@pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})])
def test_detect_chained_assignment_warning_stacklevel(
@@ -490,15 +347,9 @@ def test_detect_chained_assignment_warning_stacklevel(
df = DataFrame(np.arange(25).reshape(5, 5))
df_original = df.copy()
chained = df.loc[:3]
- with option_context("chained_assignment", "warn"):
- if not using_copy_on_write:
- with tm.assert_produces_warning(SettingWithCopyWarning) as t:
- chained[2] = rhs
- assert t[0].filename == __file__
- else:
- # INFO(CoW) no warning, and original dataframe not changed
- chained[2] = rhs
- tm.assert_frame_equal(df, df_original)
+ # INFO(CoW) no warning, and original dataframe not changed
+ chained[2] = rhs
+ tm.assert_frame_equal(df, df_original)
def test_chained_getitem_with_lists(self):
# GH6394
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 9de14b3a7c112..17492f17132fd 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -12,7 +12,6 @@
import pytz
from pandas._libs.tslibs.timezones import maybe_get_tz
-from pandas.errors import SettingWithCopyError
from pandas.core.dtypes.common import (
is_integer_dtype,
@@ -281,21 +280,15 @@ def test_dt_accessor_ambiguous_freq_conversions(self):
expected = Series(exp_values, name="xxx")
tm.assert_series_equal(ser, expected)
- def test_dt_accessor_not_writeable(self, using_copy_on_write):
+ def test_dt_accessor_not_writeable(self):
# no setting allowed
ser = Series(date_range("20130101", periods=5, freq="D"), name="xxx")
with pytest.raises(ValueError, match="modifications"):
ser.dt.hour = 5
# trying to set a copy
- msg = "modifications to a property of a datetimelike.+not supported"
- with pd.option_context("chained_assignment", "raise"):
- if using_copy_on_write:
- with tm.raises_chained_assignment_error():
- ser.dt.hour[0] = 5
- else:
- with pytest.raises(SettingWithCopyError, match=msg):
- ser.dt.hour[0] = 5
+ with tm.raises_chained_assignment_error():
+ ser.dt.hour[0] = 5
@pytest.mark.parametrize(
"method, dates",
diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py
index cb83bc5833fba..bd548eb80e182 100644
--- a/pandas/tests/series/methods/test_sort_values.py
+++ b/pandas/tests/series/methods/test_sort_values.py
@@ -79,17 +79,8 @@ def test_sort_values(self, datetime_series, using_copy_on_write):
# Series.sort_values operating on a view
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
s = df.iloc[:, 0]
-
- msg = (
- "This Series is a view of some other array, to sort in-place "
- "you must create a copy"
- )
- if using_copy_on_write:
- s.sort_values(inplace=True)
- tm.assert_series_equal(s, df.iloc[:, 0].sort_values())
- else:
- with pytest.raises(ValueError, match=msg):
- s.sort_values(inplace=True)
+ s.sort_values(inplace=True)
+ tm.assert_series_equal(s, df.iloc[:, 0].sort_values())
def test_sort_values_categorical(self):
cat = Series(Categorical(["a", "b", "b", "a"], ordered=False))
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index feba0e86c6b32..ead36ee08b407 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -46,6 +46,8 @@ def test_dask(df):
pd.set_option("compute.use_numexpr", olduse)
+# TODO(CoW) see https://github.com/pandas-dev/pandas/pull/51082
+@pytest.mark.skip(reason="not implemented with CoW")
def test_dask_ufunc():
# dask sets "compute.use_numexpr" to False, so catch the current value
# and ensure to reset it afterwards to avoid impacting other tests
diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py
index c99751dca6c9d..c5c4b234eb129 100644
--- a/pandas/tests/test_errors.py
+++ b/pandas/tests/test_errors.py
@@ -37,8 +37,6 @@
"PossibleDataLossError",
"PossiblePrecisionLoss",
"PyperclipException",
- "SettingWithCopyError",
- "SettingWithCopyWarning",
"SpecificationError",
"UnsortedIndexError",
"UnsupportedFunctionCall",
| 🥳
We shouldn't merge before the actual release is out
**`_item_cache` removal**
closes #50547
closes #29411
closes #21391
**SettingWIthCopyWarning removal**
closes #18752
closes #9767
closes #14150
closes #16550
closes #17505
closes #38270
closes #39418
closes #39448
closes #41891
closes #45513
closes #50209
closes #55451
**Others Matt thinks**
closes #19102
| https://api.github.com/repos/pandas-dev/pandas/pulls/56614 | 2023-12-24T18:17:19Z | 2024-02-04T15:18:21Z | 2024-02-04T15:18:21Z | 2024-02-05T07:50:34Z |
BUG: Added raising when merging datetime columns with timedelta columns | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..e13c81b59de20 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -822,6 +822,7 @@ Reshaping
- Bug in :func:`merge_asof` raising ``TypeError`` when ``by`` dtype is not ``object``, ``int64``, or ``uint64`` (:issue:`22794`)
- Bug in :func:`merge_asof` raising incorrect error for string dtype (:issue:`56444`)
- Bug in :func:`merge_asof` when using a :class:`Timedelta` tolerance on a :class:`ArrowDtype` column (:issue:`56486`)
+- Bug in :func:`merge` not raising when merging datetime columns with timedelta columns (:issue:`56455`)
- Bug in :func:`merge` not raising when merging string columns with numeric columns (:issue:`56441`)
- Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`)
- Bug in :meth:`DataFrame.melt` where an exception was raised if ``var_name`` was not a string (:issue:`55948`)
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index f4903023e8059..4aff99dc42250 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -1526,6 +1526,11 @@ def _maybe_coerce_merge_keys(self) -> None:
) or (lk.dtype.kind == "M" and rk.dtype.kind == "M"):
# allows datetime with different resolutions
continue
+ # datetime and timedelta not allowed
+ elif lk.dtype.kind == "M" and rk.dtype.kind == "m":
+ raise ValueError(msg)
+ elif lk.dtype.kind == "m" and rk.dtype.kind == "M":
+ raise ValueError(msg)
elif is_object_dtype(lk.dtype) and is_object_dtype(rk.dtype):
continue
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 9f832c7b1d1ca..2505d9163a6d2 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2983,3 +2983,23 @@ def test_merge_empty_frames_column_order(left_empty, right_empty):
elif right_empty:
expected.loc[:, ["C", "D"]] = np.nan
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("how", ["left", "right", "inner", "outer"])
+def test_merge_datetime_and_timedelta(how):
+ left = DataFrame({"key": Series([1, None], dtype="datetime64[ns]")})
+ right = DataFrame({"key": Series([1], dtype="timedelta64[ns]")})
+
+ msg = (
+ f"You are trying to merge on {left['key'].dtype} and {right['key'].dtype} "
+ "columns for key 'key'. If you wish to proceed you should use pd.concat"
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ left.merge(right, on="key", how=how)
+
+ msg = (
+ f"You are trying to merge on {right['key'].dtype} and {left['key'].dtype} "
+ "columns for key 'key'. If you wish to proceed you should use pd.concat"
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ right.merge(left, on="key", how=how)
| - [x] closes #56455
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56613 | 2023-12-24T15:05:23Z | 2023-12-28T17:33:26Z | 2023-12-28T17:33:26Z | 2023-12-28T17:33:36Z |
Backport PR #56595 on branch 2.2.x (TST/CLN: Inline seldom used fixture) | diff --git a/pandas/tests/arrays/categorical/conftest.py b/pandas/tests/arrays/categorical/conftest.py
deleted file mode 100644
index 37249210f28f4..0000000000000
--- a/pandas/tests/arrays/categorical/conftest.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import pytest
-
-from pandas import Categorical
-
-
-@pytest.fixture
-def factor():
- """Fixture returning a Categorical object"""
- return Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index b4215b4a6fe21..a939ee5f6f53f 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -385,7 +385,8 @@ def test_remove_unused_categories(self):
class TestCategoricalAPIWithFactor:
- def test_describe(self, factor):
+ def test_describe(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
# string type
desc = factor.describe()
assert factor.ordered
diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py
index 3377c411a7084..5e1c5c64fa660 100644
--- a/pandas/tests/arrays/categorical/test_indexing.py
+++ b/pandas/tests/arrays/categorical/test_indexing.py
@@ -21,7 +21,8 @@
class TestCategoricalIndexingWithFactor:
- def test_getitem(self, factor):
+ def test_getitem(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
assert factor[0] == "a"
assert factor[-1] == "c"
@@ -31,7 +32,8 @@ def test_getitem(self, factor):
subf = factor[np.asarray(factor) == "c"]
tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))
- def test_setitem(self, factor):
+ def test_setitem(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
# int/positional
c = factor.copy()
c[0] = "b"
diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py
index 16b941eab4830..4174d2adc810b 100644
--- a/pandas/tests/arrays/categorical/test_operators.py
+++ b/pandas/tests/arrays/categorical/test_operators.py
@@ -17,7 +17,8 @@ def test_categories_none_comparisons(self):
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
tm.assert_categorical_equal(factor, factor)
- def test_comparisons(self, factor):
+ def test_comparisons(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
result = factor[factor == "a"]
expected = factor[np.asarray(factor) == "a"]
tm.assert_categorical_equal(result, expected)
diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py
index d6f93fbbd912f..ef0315130215c 100644
--- a/pandas/tests/arrays/categorical/test_repr.py
+++ b/pandas/tests/arrays/categorical/test_repr.py
@@ -17,7 +17,8 @@
class TestCategoricalReprWithFactor:
- def test_print(self, factor, using_infer_string):
+ def test_print(self, using_infer_string):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
if using_infer_string:
expected = [
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index 5db0aa5cf510f..bac9548b932c1 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -10,8 +10,6 @@
)
import pandas._testing as tm
-START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
-
class TestDatetimeIndexOps:
def test_infer_freq(self, freq_sample):
@@ -26,6 +24,7 @@ def test_infer_freq(self, freq_sample):
class TestBusinessDatetimeIndex:
@pytest.fixture
def rng(self, freq):
+ START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
return bdate_range(START, END, freq=freq)
def test_comparison(self, rng):
diff --git a/pandas/tests/tseries/offsets/conftest.py b/pandas/tests/tseries/offsets/conftest.py
deleted file mode 100644
index 2fc846353dcb5..0000000000000
--- a/pandas/tests/tseries/offsets/conftest.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import datetime
-
-import pytest
-
-from pandas._libs.tslibs import Timestamp
-
-
-@pytest.fixture
-def dt():
- """
- Fixture for common Timestamp.
- """
- return Timestamp(datetime.datetime(2008, 1, 2))
diff --git a/pandas/tests/tseries/offsets/test_common.py b/pandas/tests/tseries/offsets/test_common.py
index 5b80b8b1c4ab4..aa4e22f71ad66 100644
--- a/pandas/tests/tseries/offsets/test_common.py
+++ b/pandas/tests/tseries/offsets/test_common.py
@@ -250,7 +250,8 @@ def test_sub(date, offset_box, offset2):
[BusinessHour, BusinessHour()],
],
)
-def test_Mult1(offset_box, offset1, dt):
+def test_Mult1(offset_box, offset1):
+ dt = Timestamp(2008, 1, 2)
assert dt + 10 * offset1 == dt + offset_box(10)
assert dt + 5 * offset1 == dt + offset_box(5)
| Backport PR #56595: TST/CLN: Inline seldom used fixture | https://api.github.com/repos/pandas-dev/pandas/pulls/56612 | 2023-12-24T14:20:09Z | 2023-12-24T16:46:25Z | 2023-12-24T16:46:25Z | 2023-12-24T16:46:25Z |
Closed: fork was outdated | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..2b961f88b6e75 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -797,6 +797,7 @@ Plotting
^^^^^^^^
- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a Matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
- Bug in :meth:`DataFrame.plot.scatter` discarding string columns (:issue:`56142`)
+- Bug in :meth:`DataFrame.plot` where bar and line plots are not aligned on the x-axis (:issue:`56611`)
- Bug in :meth:`Series.plot` when reusing an ``ax`` object failing to raise when a ``how`` keyword is passed (:issue:`55953`)
Groupby/resample/rolling
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 2979903edf360..e811411e8f1d6 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -1805,6 +1805,15 @@ def _kind(self) -> Literal["bar", "barh"]:
def orientation(self) -> PlottingOrientation:
return "vertical"
+ @final
+ def _is_ts_plot(self) -> bool:
+ # this is slightly deceptive
+ return not self.x_compat and self.use_index and self._use_dynamic_x()
+
+ @final
+ def _use_dynamic_x(self) -> bool:
+ return use_dynamic_x(self._get_ax(0), self.data)
+
def __init__(
self,
data,
@@ -1823,7 +1832,6 @@ def __init__(
self.bar_width = width
self._align = align
self._position = position
- self.tick_pos = np.arange(len(data))
if is_list_like(bottom):
bottom = np.array(bottom)
@@ -1836,6 +1844,12 @@ def __init__(
MPLPlot.__init__(self, data, **kwargs)
+ self.tick_pos = (
+ np.array(self._get_xticks(), dtype=int)
+ if (self._is_series and not self._is_ts_plot)
+ else np.arange(len(data))
+ )
+
@cache_readonly
def ax_pos(self) -> np.ndarray:
return self.tick_pos - self.tickoffset
| - [X] closes #xxxxx
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Submitting this for discussion rather than as a confirmed fix. _Should_ we be doing this (and only this), are there other cases we want to cover?
(Although I'm listed as a contributor... my previous contribution was documentation and I don't even remember what I did. Please treat me as new!)
Running tests locally:
```
49 failed, 216759 passed, 6534 skipped, 1840 xfailed, 88 xpassed, 634 warnings, 1 error in 285.27s (0:04:45)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/56611 | 2023-12-24T09:33:15Z | 2023-12-28T13:54:43Z | null | 2023-12-29T05:24:11Z |
CLN/TST: Resample fixtures | diff --git a/pandas/tests/resample/conftest.py b/pandas/tests/resample/conftest.py
index 1033d908eb22d..6c45ece5d8fb9 100644
--- a/pandas/tests/resample/conftest.py
+++ b/pandas/tests/resample/conftest.py
@@ -1,13 +1,5 @@
-from datetime import datetime
-
-import numpy as np
import pytest
-from pandas import (
- DataFrame,
- Series,
-)
-
# The various methods we support
downsample_methods = [
"min",
@@ -39,105 +31,3 @@ def downsample_method(request):
def resample_method(request):
"""Fixture for parametrization of Grouper resample methods."""
return request.param
-
-
-@pytest.fixture
-def _index_start():
- """Fixture for parametrization of index, series and frame."""
- return datetime(2005, 1, 1)
-
-
-@pytest.fixture
-def _index_end():
- """Fixture for parametrization of index, series and frame."""
- return datetime(2005, 1, 10)
-
-
-@pytest.fixture
-def _index_freq():
- """Fixture for parametrization of index, series and frame."""
- return "D"
-
-
-@pytest.fixture
-def _index_name():
- """Fixture for parametrization of index, series and frame."""
- return None
-
-
-@pytest.fixture
-def index(_index_factory, _index_start, _index_end, _index_freq, _index_name):
- """
- Fixture for parametrization of date_range, period_range and
- timedelta_range indexes
- """
- return _index_factory(_index_start, _index_end, freq=_index_freq, name=_index_name)
-
-
-@pytest.fixture
-def _static_values(index):
- """
- Fixture for parametrization of values used in parametrization of
- Series and DataFrames with date_range, period_range and
- timedelta_range indexes
- """
- return np.arange(len(index))
-
-
-@pytest.fixture
-def _series_name():
- """
- Fixture for parametrization of Series name for Series used with
- date_range, period_range and timedelta_range indexes
- """
- return None
-
-
-@pytest.fixture
-def series(index, _series_name, _static_values):
- """
- Fixture for parametrization of Series with date_range, period_range and
- timedelta_range indexes
- """
- return Series(_static_values, index=index, name=_series_name)
-
-
-@pytest.fixture
-def empty_series_dti(series):
- """
- Fixture for parametrization of empty Series with date_range,
- period_range and timedelta_range indexes
- """
- return series[:0]
-
-
-@pytest.fixture
-def frame(index, _series_name, _static_values):
- """
- Fixture for parametrization of DataFrame with date_range, period_range
- and timedelta_range indexes
- """
- # _series_name is intentionally unused
- return DataFrame({"value": _static_values}, index=index)
-
-
-@pytest.fixture
-def empty_frame_dti(series):
- """
- Fixture for parametrization of empty DataFrame with date_range,
- period_range and timedelta_range indexes
- """
- index = series.index[:0]
- return DataFrame(index=index)
-
-
-@pytest.fixture
-def series_and_frame(frame_or_series, series, frame):
- """
- Fixture for parametrization of Series and DataFrame with date_range,
- period_range and timedelta_range indexes
- """
- if frame_or_series == Series:
- return series
- if frame_or_series == DataFrame:
- return frame
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py
index 50644e33e45e1..f20518c7be98a 100644
--- a/pandas/tests/resample/test_base.py
+++ b/pandas/tests/resample/test_base.py
@@ -21,54 +21,41 @@
from pandas.core.indexes.timedeltas import timedelta_range
from pandas.core.resample import _asfreq_compat
-# a fixture value can be overridden by the test parameter value. Note that the
-# value of the fixture can be overridden this way even if the test doesn't use
-# it directly (doesn't mention it in the function prototype).
-# see https://docs.pytest.org/en/latest/fixture.html#override-a-fixture-with-direct-test-parametrization # noqa: E501
-# in this module we override the fixture values defined in conftest.py
-# tuples of '_index_factory,_series_name,_index_start,_index_end'
-DATE_RANGE = (date_range, "dti", datetime(2005, 1, 1), datetime(2005, 1, 10))
-PERIOD_RANGE = (period_range, "pi", datetime(2005, 1, 1), datetime(2005, 1, 10))
-TIMEDELTA_RANGE = (timedelta_range, "tdi", "1 day", "10 day")
-
-all_ts = pytest.mark.parametrize(
- "_index_factory,_series_name,_index_start,_index_end",
- [DATE_RANGE, PERIOD_RANGE, TIMEDELTA_RANGE],
-)
-
-
-@pytest.fixture
-def create_index(_index_factory):
- def _create_index(*args, **kwargs):
- """return the _index_factory created using the args, kwargs"""
- return _index_factory(*args, **kwargs)
-
- return _create_index
-
@pytest.mark.parametrize("freq", ["2D", "1h"])
@pytest.mark.parametrize(
- "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE]
+ "index",
+ [
+ timedelta_range("1 day", "10 day", freq="D"),
+ date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ ],
)
-def test_asfreq(series_and_frame, freq, create_index):
- obj = series_and_frame
+@pytest.mark.parametrize("klass", [DataFrame, Series])
+def test_asfreq(klass, index, freq):
+ obj = klass(range(len(index)), index=index)
+ idx_range = date_range if isinstance(index, DatetimeIndex) else timedelta_range
result = obj.resample(freq).asfreq()
- new_index = create_index(obj.index[0], obj.index[-1], freq=freq)
+ new_index = idx_range(obj.index[0], obj.index[-1], freq=freq)
expected = obj.reindex(new_index)
tm.assert_almost_equal(result, expected)
@pytest.mark.parametrize(
- "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE]
+ "index",
+ [
+ timedelta_range("1 day", "10 day", freq="D"),
+ date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ ],
)
-def test_asfreq_fill_value(series, create_index):
+def test_asfreq_fill_value(index):
# test for fill value during resampling, issue 3715
- ser = series
+ ser = Series(range(len(index)), index=index, name="a")
+ idx_range = date_range if isinstance(index, DatetimeIndex) else timedelta_range
result = ser.resample("1h").asfreq()
- new_index = create_index(ser.index[0], ser.index[-1], freq="1h")
+ new_index = idx_range(ser.index[0], ser.index[-1], freq="1h")
expected = ser.reindex(new_index)
tm.assert_series_equal(result, expected)
@@ -76,15 +63,22 @@ def test_asfreq_fill_value(series, create_index):
frame = ser.astype("float").to_frame("value")
frame.iloc[1] = None
result = frame.resample("1h").asfreq(fill_value=4.0)
- new_index = create_index(frame.index[0], frame.index[-1], freq="1h")
+ new_index = idx_range(frame.index[0], frame.index[-1], freq="1h")
expected = frame.reindex(new_index, fill_value=4.0)
tm.assert_frame_equal(result, expected)
-@all_ts
-def test_resample_interpolate(frame):
+@pytest.mark.parametrize(
+ "index",
+ [
+ timedelta_range("1 day", "10 day", freq="D"),
+ date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ period_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ ],
+)
+def test_resample_interpolate(index):
# GH#12925
- df = frame
+ df = DataFrame(range(len(index)), index=index)
warn = None
if isinstance(df.index, PeriodIndex):
warn = FutureWarning
@@ -106,12 +100,19 @@ def test_raises_on_non_datetimelike_index():
xp.resample("YE")
-@all_ts
+@pytest.mark.parametrize(
+ "index",
+ [
+ PeriodIndex([], freq="D", name="a"),
+ DatetimeIndex([], name="a"),
+ TimedeltaIndex([], name="a"),
+ ],
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
-def test_resample_empty_series(freq, empty_series_dti, resample_method):
+def test_resample_empty_series(freq, index, resample_method):
# GH12771 & GH12868
- ser = empty_series_dti
+ ser = Series(index=index, dtype=float)
if freq == "ME" and isinstance(ser.index, TimedeltaIndex):
msg = (
"Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
@@ -147,7 +148,6 @@ def test_resample_empty_series(freq, empty_series_dti, resample_method):
assert result.index.freq == expected.index.freq
-@all_ts
@pytest.mark.parametrize(
"freq",
[
@@ -156,11 +156,10 @@ def test_resample_empty_series(freq, empty_series_dti, resample_method):
"h",
],
)
-def test_resample_nat_index_series(freq, series, resample_method):
+def test_resample_nat_index_series(freq, resample_method):
# GH39227
- ser = series.copy()
- ser.index = PeriodIndex([NaT] * len(ser), freq=freq)
+ ser = Series(range(5), index=PeriodIndex([NaT] * 5, freq=freq))
msg = "Resampling with a PeriodIndex is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
@@ -179,12 +178,19 @@ def test_resample_nat_index_series(freq, series, resample_method):
assert result.index.freq == expected.index.freq
-@all_ts
+@pytest.mark.parametrize(
+ "index",
+ [
+ PeriodIndex([], freq="D", name="a"),
+ DatetimeIndex([], name="a"),
+ TimedeltaIndex([], name="a"),
+ ],
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
@pytest.mark.parametrize("resample_method", ["count", "size"])
-def test_resample_count_empty_series(freq, empty_series_dti, resample_method):
+def test_resample_count_empty_series(freq, index, resample_method):
# GH28427
- ser = empty_series_dti
+ ser = Series(index=index)
if freq == "ME" and isinstance(ser.index, TimedeltaIndex):
msg = (
"Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
@@ -213,11 +219,13 @@ def test_resample_count_empty_series(freq, empty_series_dti, resample_method):
tm.assert_series_equal(result, expected)
-@all_ts
+@pytest.mark.parametrize(
+ "index", [DatetimeIndex([]), TimedeltaIndex([]), PeriodIndex([], freq="D")]
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
-def test_resample_empty_dataframe(empty_frame_dti, freq, resample_method):
+def test_resample_empty_dataframe(index, freq, resample_method):
# GH13212
- df = empty_frame_dti
+ df = DataFrame(index=index)
# count retains dimensions too
if freq == "ME" and isinstance(df.index, TimedeltaIndex):
msg = (
@@ -261,12 +269,13 @@ def test_resample_empty_dataframe(empty_frame_dti, freq, resample_method):
# test size for GH13212 (currently stays as df)
-@all_ts
+@pytest.mark.parametrize(
+ "index", [DatetimeIndex([]), TimedeltaIndex([]), PeriodIndex([], freq="D")]
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
-def test_resample_count_empty_dataframe(freq, empty_frame_dti):
+def test_resample_count_empty_dataframe(freq, index):
# GH28427
-
- empty_frame_dti["a"] = []
+ empty_frame_dti = DataFrame(index=index, columns=Index(["a"], dtype=object))
if freq == "ME" and isinstance(empty_frame_dti.index, TimedeltaIndex):
msg = (
@@ -295,12 +304,14 @@ def test_resample_count_empty_dataframe(freq, empty_frame_dti):
tm.assert_frame_equal(result, expected)
-@all_ts
+@pytest.mark.parametrize(
+ "index", [DatetimeIndex([]), TimedeltaIndex([]), PeriodIndex([], freq="D")]
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
-def test_resample_size_empty_dataframe(freq, empty_frame_dti):
+def test_resample_size_empty_dataframe(freq, index):
# GH28427
- empty_frame_dti["a"] = []
+ empty_frame_dti = DataFrame(index=index, columns=Index(["a"], dtype=object))
if freq == "ME" and isinstance(empty_frame_dti.index, TimedeltaIndex):
msg = (
@@ -361,27 +372,34 @@ def test_resample_empty_dtypes(index, dtype, resample_method):
pass
-@all_ts
+@pytest.mark.parametrize(
+ "index",
+ [
+ PeriodIndex([], freq="D", name="a"),
+ DatetimeIndex([], name="a"),
+ TimedeltaIndex([], name="a"),
+ ],
+)
@pytest.mark.parametrize("freq", ["ME", "D", "h"])
-def test_apply_to_empty_series(empty_series_dti, freq):
+def test_apply_to_empty_series(index, freq):
# GH 14313
- ser = empty_series_dti
+ ser = Series(index=index)
- if freq == "ME" and isinstance(empty_series_dti.index, TimedeltaIndex):
+ if freq == "ME" and isinstance(ser.index, TimedeltaIndex):
msg = (
"Resampling on a TimedeltaIndex requires fixed-duration `freq`, "
"e.g. '24h' or '3D', not <MonthEnd>"
)
with pytest.raises(ValueError, match=msg):
- empty_series_dti.resample(freq)
+ ser.resample(freq)
return
- elif freq == "ME" and isinstance(empty_series_dti.index, PeriodIndex):
+ elif freq == "ME" and isinstance(ser.index, PeriodIndex):
# index is PeriodIndex, so convert to corresponding Period freq
freq = "M"
msg = "Resampling with a PeriodIndex"
warn = None
- if isinstance(empty_series_dti.index, PeriodIndex):
+ if isinstance(ser.index, PeriodIndex):
warn = FutureWarning
with tm.assert_produces_warning(warn, match=msg):
@@ -394,9 +412,17 @@ def test_apply_to_empty_series(empty_series_dti, freq):
tm.assert_series_equal(result, expected, check_dtype=False)
-@all_ts
-def test_resampler_is_iterable(series):
+@pytest.mark.parametrize(
+ "index",
+ [
+ timedelta_range("1 day", "10 day", freq="D"),
+ date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ period_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ ],
+)
+def test_resampler_is_iterable(index):
# GH 15314
+ series = Series(range(len(index)), index=index)
freq = "h"
tg = Grouper(freq=freq, convention="start")
msg = "Resampling with a PeriodIndex"
@@ -414,16 +440,23 @@ def test_resampler_is_iterable(series):
tm.assert_series_equal(rv, gv)
-@all_ts
-def test_resample_quantile(series):
+@pytest.mark.parametrize(
+ "index",
+ [
+ timedelta_range("1 day", "10 day", freq="D"),
+ date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ period_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D"),
+ ],
+)
+def test_resample_quantile(index):
# GH 15023
- ser = series
+ ser = Series(range(len(index)), index=index)
q = 0.75
freq = "h"
msg = "Resampling with a PeriodIndex"
warn = None
- if isinstance(series.index, PeriodIndex):
+ if isinstance(ser.index, PeriodIndex):
warn = FutureWarning
with tm.assert_produces_warning(warn, match=msg):
result = ser.resample(freq).quantile(q)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 80583f5d3c5f2..0dfe9877c4f86 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -36,21 +36,6 @@
from pandas.tseries.offsets import Minute
-@pytest.fixture()
-def _index_factory():
- return date_range
-
-
-@pytest.fixture
-def _index_freq():
- return "Min"
-
-
-@pytest.fixture
-def _static_values(index):
- return np.random.default_rng(2).random(len(index))
-
-
@pytest.fixture(params=["s", "ms", "us", "ns"])
def unit(request):
return request.param
@@ -69,7 +54,8 @@ def _simple_date_range_series(start, end, freq="D"):
return _simple_date_range_series
-def test_custom_grouper(index, unit):
+def test_custom_grouper(unit):
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="Min")
dti = index.as_unit(unit)
s = Series(np.array([1] * len(dti)), index=dti, dtype="int64")
@@ -105,7 +91,8 @@ def test_custom_grouper(index, unit):
tm.assert_series_equal(result, expect)
-def test_custom_grouper_df(index, unit):
+def test_custom_grouper_df(unit):
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
b = Grouper(freq=Minute(5), closed="right", label="right")
dti = index.as_unit(unit)
df = DataFrame(
@@ -117,10 +104,6 @@ def test_custom_grouper_df(index, unit):
assert len(r.index) == 2593
-@pytest.mark.parametrize(
- "_index_start,_index_end,_index_name",
- [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
-)
@pytest.mark.parametrize(
"closed, expected",
[
@@ -142,8 +125,10 @@ def test_custom_grouper_df(index, unit):
),
],
)
-def test_resample_basic(series, closed, expected, unit):
- s = series
+def test_resample_basic(closed, expected, unit):
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ s = Series(range(len(index)), index=index)
+ s.index.name = "index"
s.index = s.index.as_unit(unit)
expected = expected(s)
expected.index = expected.index.as_unit(unit)
@@ -175,8 +160,10 @@ def test_resample_integerarray(unit):
tm.assert_series_equal(result, expected)
-def test_resample_basic_grouper(series, unit):
- s = series
+def test_resample_basic_grouper(unit):
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ s = Series(range(len(index)), index=index)
+ s.index.name = "index"
s.index = s.index.as_unit(unit)
result = s.resample("5Min").last()
grouper = Grouper(freq=Minute(5), closed="left", label="left")
@@ -187,32 +174,28 @@ def test_resample_basic_grouper(series, unit):
@pytest.mark.filterwarnings(
"ignore:The 'convention' keyword in Series.resample:FutureWarning"
)
-@pytest.mark.parametrize(
- "_index_start,_index_end,_index_name",
- [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
-)
@pytest.mark.parametrize(
"keyword,value",
[("label", "righttt"), ("closed", "righttt"), ("convention", "starttt")],
)
-def test_resample_string_kwargs(series, keyword, value, unit):
+def test_resample_string_kwargs(keyword, value, unit):
# see gh-19303
# Check that wrong keyword argument strings raise an error
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ series = Series(range(len(index)), index=index)
+ series.index.name = "index"
series.index = series.index.as_unit(unit)
msg = f"Unsupported value {value} for `{keyword}`"
with pytest.raises(ValueError, match=msg):
series.resample("5min", **({keyword: value}))
-@pytest.mark.parametrize(
- "_index_start,_index_end,_index_name",
- [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
-)
-def test_resample_how(series, downsample_method, unit):
+def test_resample_how(downsample_method, unit):
if downsample_method == "ohlc":
pytest.skip("covered by test_resample_how_ohlc")
-
- s = series
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ s = Series(range(len(index)), index=index)
+ s.index.name = "index"
s.index = s.index.as_unit(unit)
grouplist = np.ones_like(s)
grouplist[0] = 0
@@ -230,12 +213,10 @@ def test_resample_how(series, downsample_method, unit):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize(
- "_index_start,_index_end,_index_name",
- [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")],
-)
-def test_resample_how_ohlc(series, unit):
- s = series
+def test_resample_how_ohlc(unit):
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ s = Series(range(len(index)), index=index)
+ s.index.name = "index"
s.index = s.index.as_unit(unit)
grouplist = np.ones_like(s)
grouplist[0] = 0
@@ -558,8 +539,10 @@ def test_nearest_upsample_with_limit(tz_aware_fixture, freq, rule, unit):
tm.assert_series_equal(result, expected)
-def test_resample_ohlc(series, unit):
- s = series
+def test_resample_ohlc(unit):
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="Min")
+ s = Series(range(len(index)), index=index)
+ s.index.name = "index"
s.index = s.index.as_unit(unit)
grouper = Grouper(freq=Minute(5))
@@ -1854,8 +1837,12 @@ def test_resample_datetime_values(unit):
tm.assert_series_equal(res, exp)
-def test_resample_apply_with_additional_args(series, unit):
+def test_resample_apply_with_additional_args(unit):
# GH 14615
+ index = date_range("1/1/2000 00:00:00", "1/1/2000 00:13:00", freq="Min")
+ series = Series(range(len(index)), index=index)
+ series.index.name = "index"
+
def f(data, add_arg):
return np.mean(data) * add_arg
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index eb80f56dd7d4b..cf77238a553d0 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -35,16 +35,6 @@
)
-@pytest.fixture()
-def _index_factory():
- return period_range
-
-
-@pytest.fixture
-def _series_name():
- return "pi"
-
-
@pytest.fixture
def simple_period_range_series():
"""
@@ -69,11 +59,12 @@ def _simple_period_range_series(start, end, freq="D"):
class TestPeriodIndex:
@pytest.mark.parametrize("freq", ["2D", "1h", "2h"])
@pytest.mark.parametrize("kind", ["period", None, "timestamp"])
- def test_asfreq(self, series_and_frame, freq, kind):
+ @pytest.mark.parametrize("klass", [DataFrame, Series])
+ def test_asfreq(self, klass, freq, kind):
# GH 12884, 15944
# make sure .asfreq() returns PeriodIndex (except kind='timestamp')
- obj = series_and_frame
+ obj = klass(range(5), index=period_range("2020-01-01", periods=5))
if kind == "timestamp":
expected = obj.to_timestamp().resample(freq).asfreq()
else:
@@ -86,10 +77,11 @@ def test_asfreq(self, series_and_frame, freq, kind):
result = obj.resample(freq, kind=kind).asfreq()
tm.assert_almost_equal(result, expected)
- def test_asfreq_fill_value(self, series):
+ def test_asfreq_fill_value(self):
# test for fill value during resampling, issue 3715
- s = series
+ index = period_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
+ s = Series(range(len(index)), index=index)
new_index = date_range(
s.index[0].to_timestamp(how="start"),
(s.index[-1]).to_timestamp(how="start"),
@@ -116,9 +108,10 @@ def test_asfreq_fill_value(self, series):
@pytest.mark.parametrize("freq", ["h", "12h", "2D", "W"])
@pytest.mark.parametrize("kind", [None, "period", "timestamp"])
@pytest.mark.parametrize("kwargs", [{"on": "date"}, {"level": "d"}])
- def test_selection(self, index, freq, kind, kwargs):
+ def test_selection(self, freq, kind, kwargs):
# This is a bug, these should be implemented
# GH 14008
+ index = period_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
rng = np.arange(len(index), dtype=np.int64)
df = DataFrame(
{"date": index, "a": rng},
@@ -1014,13 +1007,14 @@ def test_resample_t_l_deprecated(self):
offsets.BusinessHour(2),
],
)
- def test_asfreq_invalid_period_freq(self, offset, series_and_frame):
+ @pytest.mark.parametrize("klass", [DataFrame, Series])
+ def test_asfreq_invalid_period_freq(self, offset, klass):
# GH#9586
msg = f"Invalid offset: '{offset.base}' for converting time series "
- df = series_and_frame
+ obj = klass(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
- df.asfreq(freq=offset)
+ obj.asfreq(freq=offset)
@pytest.mark.parametrize(
@@ -1033,11 +1027,12 @@ def test_asfreq_invalid_period_freq(self, offset, series_and_frame):
("2Y-MAR", "2YE-MAR"),
],
)
-def test_resample_frequency_ME_QE_YE_error_message(series_and_frame, freq, freq_depr):
+@pytest.mark.parametrize("klass", [DataFrame, Series])
+def test_resample_frequency_ME_QE_YE_error_message(klass, freq, freq_depr):
# GH#9586
msg = f"for Period, please use '{freq[1:]}' instead of '{freq_depr[1:]}'"
- obj = series_and_frame
+ obj = klass(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
obj.resample(freq_depr)
@@ -1062,10 +1057,11 @@ def test_corner_cases_period(simple_period_range_series):
"2BYE-MAR",
],
)
-def test_resample_frequency_invalid_freq(series_and_frame, freq_depr):
+@pytest.mark.parametrize("klass", [DataFrame, Series])
+def test_resample_frequency_invalid_freq(klass, freq_depr):
# GH#9586
msg = f"Invalid frequency: {freq_depr[1:]}"
- obj = series_and_frame
+ obj = klass(range(5), index=period_range("2020-01-01", periods=5))
with pytest.raises(ValueError, match=msg):
obj.resample(freq_depr)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56608 | 2023-12-23T03:44:04Z | 2023-12-28T19:05:57Z | 2023-12-28T19:05:57Z | 2023-12-28T19:06:00Z |
Start 2.3.0 | - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56603 | 2023-12-22T19:13:57Z | 2023-12-22T19:14:56Z | 2023-12-22T19:14:56Z | 2023-12-22T19:14:57Z | |
BUG: Fix inconsistency when constructing a Series with large integers | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5de5bd58bd35f..2f6e97dd3db50 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -928,6 +928,17 @@ Reshaping
Sparse
^^^^^^
- Bug in :meth:`SparseArray.take` when using a different fill value than the array's fill value (:issue:`55181`)
+-
+
+ExtensionArray
+^^^^^^^^^^^^^^
+- Bug in :class:`Series` constructor giving inconsistent precision for large integer (:issue:`56566`)
+-
+
+Styler
+^^^^^^
+-
+-
Other
^^^^^
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index d41a9c80a10ec..b3fbb75e330ae 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -47,6 +47,8 @@
maybe_promote,
)
from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
is_list_like,
is_object_dtype,
is_string_dtype,
@@ -503,11 +505,22 @@ def sanitize_masked_array(data: ma.MaskedArray) -> np.ndarray:
Convert numpy MaskedArray to ensure mask is softened.
"""
mask = ma.getmaskarray(data)
+ original = data
+ original_dtype = data.dtype
if mask.any():
dtype, fill_value = maybe_promote(data.dtype, np.nan)
dtype = cast(np.dtype, dtype)
data = ma.asarray(data.astype(dtype, copy=True))
data.soften_mask() # set hardmask False if it was True
+ if not mask.all():
+ idx = np.unravel_index(np.nanargmax(data, axis=None), data.shape)
+ if not mask[idx] and int(data[idx]) != original[idx]:
+ if (
+ is_integer_dtype(original_dtype)
+ and is_float_dtype(data.dtype)
+ and len(data) > 0
+ ):
+ data = ma.asarray(original, "object")
data[mask] = fill_value
else:
data = data.copy()
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 55ca1f98f6d6c..f7724ce0a306c 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -2157,6 +2157,36 @@ def test_inference_on_pandas_objects(self):
result = Series(idx)
assert result.dtype != np.object_
+ def test_series_constructor_maskedarray_int_overflow(self):
+ # GH#56566
+ mx = ma.masked_array(
+ [
+ 4873214862074861312,
+ 4875446630161458944,
+ 4824652147895424384,
+ 0,
+ 3526420114272476800,
+ ],
+ mask=[0, 0, 0, 1, 0],
+ )
+ result = Series(mx, dtype="Int64")
+ expected = Series(
+ IntegerArray(
+ np.array(
+ [
+ 4873214862074861312,
+ 4875446630161458944,
+ 4824652147895424384,
+ 0,
+ 3526420114272476800,
+ ],
+ dtype="int64",
+ ),
+ np.array([0, 0, 0, 1, 0], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
class TestSeriesConstructorIndexCoercion:
def test_series_constructor_datetimelike_index_coercion(self):
| - [x] closes #56566
- [x] [Tests added and passed
- [x] All [code checks passed]
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56598 | 2023-12-22T10:04:31Z | 2024-01-23T09:54:22Z | null | 2024-01-23T09:54:22Z |
CI: Move target for the deprecations bot | diff --git a/.github/workflows/deprecation-tracking-bot.yml b/.github/workflows/deprecation-tracking-bot.yml
index ec71daf6f84ab..3d4cab7be09c5 100644
--- a/.github/workflows/deprecation-tracking-bot.yml
+++ b/.github/workflows/deprecation-tracking-bot.yml
@@ -19,7 +19,7 @@ jobs:
issues: write
runs-on: ubuntu-22.04
env:
- DEPRECATION_TRACKER_ISSUE: 50578
+ DEPRECATION_TRACKER_ISSUE: 56596
steps:
- uses: actions/github-script@v7
id: update-deprecation-issue
| cc @lithomas1 for after the rc
Just making sure that we don't forget this | https://api.github.com/repos/pandas-dev/pandas/pulls/56597 | 2023-12-22T09:59:46Z | 2023-12-23T18:56:41Z | 2023-12-23T18:56:41Z | 2023-12-23T18:56:44Z |
TST/CLN: Inline seldom used fixture | diff --git a/pandas/tests/arrays/categorical/conftest.py b/pandas/tests/arrays/categorical/conftest.py
deleted file mode 100644
index 37249210f28f4..0000000000000
--- a/pandas/tests/arrays/categorical/conftest.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import pytest
-
-from pandas import Categorical
-
-
-@pytest.fixture
-def factor():
- """Fixture returning a Categorical object"""
- return Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index b4215b4a6fe21..a939ee5f6f53f 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -385,7 +385,8 @@ def test_remove_unused_categories(self):
class TestCategoricalAPIWithFactor:
- def test_describe(self, factor):
+ def test_describe(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
# string type
desc = factor.describe()
assert factor.ordered
diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py
index 3377c411a7084..5e1c5c64fa660 100644
--- a/pandas/tests/arrays/categorical/test_indexing.py
+++ b/pandas/tests/arrays/categorical/test_indexing.py
@@ -21,7 +21,8 @@
class TestCategoricalIndexingWithFactor:
- def test_getitem(self, factor):
+ def test_getitem(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
assert factor[0] == "a"
assert factor[-1] == "c"
@@ -31,7 +32,8 @@ def test_getitem(self, factor):
subf = factor[np.asarray(factor) == "c"]
tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))
- def test_setitem(self, factor):
+ def test_setitem(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
# int/positional
c = factor.copy()
c[0] = "b"
diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py
index 16b941eab4830..4174d2adc810b 100644
--- a/pandas/tests/arrays/categorical/test_operators.py
+++ b/pandas/tests/arrays/categorical/test_operators.py
@@ -17,7 +17,8 @@ def test_categories_none_comparisons(self):
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
tm.assert_categorical_equal(factor, factor)
- def test_comparisons(self, factor):
+ def test_comparisons(self):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
result = factor[factor == "a"]
expected = factor[np.asarray(factor) == "a"]
tm.assert_categorical_equal(result, expected)
diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py
index d6f93fbbd912f..ef0315130215c 100644
--- a/pandas/tests/arrays/categorical/test_repr.py
+++ b/pandas/tests/arrays/categorical/test_repr.py
@@ -17,7 +17,8 @@
class TestCategoricalReprWithFactor:
- def test_print(self, factor, using_infer_string):
+ def test_print(self, using_infer_string):
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
if using_infer_string:
expected = [
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index 5db0aa5cf510f..bac9548b932c1 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -10,8 +10,6 @@
)
import pandas._testing as tm
-START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
-
class TestDatetimeIndexOps:
def test_infer_freq(self, freq_sample):
@@ -26,6 +24,7 @@ def test_infer_freq(self, freq_sample):
class TestBusinessDatetimeIndex:
@pytest.fixture
def rng(self, freq):
+ START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
return bdate_range(START, END, freq=freq)
def test_comparison(self, rng):
diff --git a/pandas/tests/tseries/offsets/conftest.py b/pandas/tests/tseries/offsets/conftest.py
deleted file mode 100644
index 2fc846353dcb5..0000000000000
--- a/pandas/tests/tseries/offsets/conftest.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import datetime
-
-import pytest
-
-from pandas._libs.tslibs import Timestamp
-
-
-@pytest.fixture
-def dt():
- """
- Fixture for common Timestamp.
- """
- return Timestamp(datetime.datetime(2008, 1, 2))
diff --git a/pandas/tests/tseries/offsets/test_common.py b/pandas/tests/tseries/offsets/test_common.py
index 5b80b8b1c4ab4..aa4e22f71ad66 100644
--- a/pandas/tests/tseries/offsets/test_common.py
+++ b/pandas/tests/tseries/offsets/test_common.py
@@ -250,7 +250,8 @@ def test_sub(date, offset_box, offset2):
[BusinessHour, BusinessHour()],
],
)
-def test_Mult1(offset_box, offset1, dt):
+def test_Mult1(offset_box, offset1):
+ dt = Timestamp(2008, 1, 2)
assert dt + 10 * offset1 == dt + offset_box(10)
assert dt + 5 * offset1 == dt + offset_box(5)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56595 | 2023-12-22T01:09:35Z | 2023-12-24T14:19:14Z | 2023-12-24T14:19:14Z | 2023-12-24T19:56:28Z |
DEPR: the method is_anchored() for offsets | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 5b955aa45219a..3ef1abff53d18 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -587,11 +587,13 @@ Other Deprecations
- Deprecated :func:`pd.core.internals.api.make_block`, use public APIs instead (:issue:`40226`)
- Deprecated :func:`read_gbq` and :meth:`DataFrame.to_gbq`. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`)
- Deprecated :meth:`.DataFrameGroupBy.fillna` and :meth:`.SeriesGroupBy.fillna`; use :meth:`.DataFrameGroupBy.ffill`, :meth:`.DataFrameGroupBy.bfill` for forward and backward filling or :meth:`.DataFrame.fillna` to fill with a single value (or the Series equivalents) (:issue:`55718`)
+- Deprecated :meth:`DateOffset.is_anchored`, use ``obj.n == 1`` for non-Tick subclasses (for Tick this was always False) (:issue:`55388`)
- Deprecated :meth:`DatetimeArray.__init__` and :meth:`TimedeltaArray.__init__`, use :func:`array` instead (:issue:`55623`)
- Deprecated :meth:`Index.format`, use ``index.astype(str)`` or ``index.map(formatter)`` instead (:issue:`55413`)
- Deprecated :meth:`Series.ravel`, the underlying array is already 1D, so ravel is not necessary (:issue:`52511`)
- Deprecated :meth:`Series.resample` and :meth:`DataFrame.resample` with a :class:`PeriodIndex` (and the 'convention' keyword), convert to :class:`DatetimeIndex` (with ``.to_timestamp()``) before resampling instead (:issue:`53481`)
- Deprecated :meth:`Series.view`, use :meth:`Series.astype` instead to change the dtype (:issue:`20251`)
+- Deprecated :meth:`offsets.Tick.is_anchored`, use ``False`` instead (:issue:`55388`)
- Deprecated ``core.internals`` members ``Block``, ``ExtensionBlock``, and ``DatetimeTZBlock``, use public APIs instead (:issue:`55139`)
- Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`)
- Deprecated accepting a type as an argument in :meth:`Index.view`, call without any arguments instead (:issue:`55709`)
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index b3788b6003e67..3a339171d0da2 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -756,11 +756,14 @@ cdef class BaseOffset:
raise ValueError(f"{self} is a non-fixed frequency")
def is_anchored(self) -> bool:
- # TODO: Does this make sense for the general case? It would help
- # if there were a canonical docstring for what is_anchored means.
+ # GH#55388
"""
Return boolean whether the frequency is a unit frequency (n=1).
+ .. deprecated:: 2.2.0
+ is_anchored is deprecated and will be removed in a future version.
+ Use ``obj.n == 1`` instead.
+
Examples
--------
>>> pd.DateOffset().is_anchored()
@@ -768,6 +771,12 @@ cdef class BaseOffset:
>>> pd.DateOffset(2).is_anchored()
False
"""
+ warnings.warn(
+ f"{type(self).__name__}.is_anchored is deprecated and will be removed "
+ f"in a future version, please use \'obj.n == 1\' instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.n == 1
# ------------------------------------------------------------------
@@ -954,6 +963,27 @@ cdef class Tick(SingleConstructorOffset):
return True
def is_anchored(self) -> bool:
+ # GH#55388
+ """
+ Return False.
+
+ .. deprecated:: 2.2.0
+ is_anchored is deprecated and will be removed in a future version.
+ Use ``False`` instead.
+
+ Examples
+ --------
+ >>> pd.offsets.Hour().is_anchored()
+ False
+ >>> pd.offsets.Hour(2).is_anchored()
+ False
+ """
+ warnings.warn(
+ f"{type(self).__name__}.is_anchored is deprecated and will be removed "
+ f"in a future version, please use False instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return False
# This is identical to BaseOffset.__hash__, but has to be redefined here
@@ -2663,6 +2693,13 @@ cdef class QuarterOffset(SingleConstructorOffset):
return f"{self._prefix}-{month}"
def is_anchored(self) -> bool:
+ warnings.warn(
+ f"{type(self).__name__}.is_anchored is deprecated and will be removed "
+ f"in a future version, please use \'obj.n == 1 "
+ f"and obj.startingMonth is not None\' instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.n == 1 and self.startingMonth is not None
def is_on_offset(self, dt: datetime) -> bool:
@@ -3308,6 +3345,13 @@ cdef class Week(SingleConstructorOffset):
self._cache = state.pop("_cache", {})
def is_anchored(self) -> bool:
+ warnings.warn(
+ f"{type(self).__name__}.is_anchored is deprecated and will be removed "
+ f"in a future version, please use \'obj.n == 1 "
+ f"and obj.weekday is not None\' instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.n == 1 and self.weekday is not None
@apply_wraps
@@ -3597,6 +3641,12 @@ cdef class FY5253Mixin(SingleConstructorOffset):
self.variation = state.pop("variation")
def is_anchored(self) -> bool:
+ warnings.warn(
+ f"{type(self).__name__}.is_anchored is deprecated and will be removed "
+ f"in a future version, please use \'obj.n == 1\' instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return (
self.n == 1 and self.startingMonth is not None and self.weekday is not None
)
diff --git a/pandas/tests/indexes/interval/test_interval_range.py b/pandas/tests/indexes/interval/test_interval_range.py
index d4d4a09c44d13..e8de59f84bcc6 100644
--- a/pandas/tests/indexes/interval/test_interval_range.py
+++ b/pandas/tests/indexes/interval/test_interval_range.py
@@ -84,9 +84,7 @@ def test_constructor_timestamp(self, closed, name, freq, periods, tz):
tm.assert_index_equal(result, expected)
# GH 20976: linspace behavior defined from start/end/periods
- if not breaks.freq.is_anchored() and tz is None:
- # matches expected only for non-anchored offsets and tz naive
- # (anchored/DST transitions cause unequal spacing in expected)
+ if not breaks.freq.n == 1 and tz is None:
result = interval_range(
start=start, end=end, periods=periods, name=name, closed=closed
)
diff --git a/pandas/tests/tseries/offsets/test_business_quarter.py b/pandas/tests/tseries/offsets/test_business_quarter.py
index 44a7f16ab039d..6d7a115054b7f 100644
--- a/pandas/tests/tseries/offsets/test_business_quarter.py
+++ b/pandas/tests/tseries/offsets/test_business_quarter.py
@@ -9,6 +9,7 @@
import pytest
+import pandas._testing as tm
from pandas.tests.tseries.offsets.common import (
assert_is_on_offset,
assert_offset_equal,
@@ -54,9 +55,12 @@ def test_repr(self):
assert repr(BQuarterBegin(startingMonth=1)) == expected
def test_is_anchored(self):
- assert BQuarterBegin(startingMonth=1).is_anchored()
- assert BQuarterBegin().is_anchored()
- assert not BQuarterBegin(2, startingMonth=1).is_anchored()
+ msg = "BQuarterBegin.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert BQuarterBegin(startingMonth=1).is_anchored()
+ assert BQuarterBegin().is_anchored()
+ assert not BQuarterBegin(2, startingMonth=1).is_anchored()
def test_offset_corner_case(self):
# corner
@@ -177,9 +181,12 @@ def test_repr(self):
assert repr(BQuarterEnd(startingMonth=1)) == expected
def test_is_anchored(self):
- assert BQuarterEnd(startingMonth=1).is_anchored()
- assert BQuarterEnd().is_anchored()
- assert not BQuarterEnd(2, startingMonth=1).is_anchored()
+ msg = "BQuarterEnd.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert BQuarterEnd(startingMonth=1).is_anchored()
+ assert BQuarterEnd().is_anchored()
+ assert not BQuarterEnd(2, startingMonth=1).is_anchored()
def test_offset_corner_case(self):
# corner
diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py
index 7f8c34bc6832e..824e66a1ddef1 100644
--- a/pandas/tests/tseries/offsets/test_fiscal.py
+++ b/pandas/tests/tseries/offsets/test_fiscal.py
@@ -7,6 +7,7 @@
import pytest
from pandas import Timestamp
+import pandas._testing as tm
from pandas.tests.tseries.offsets.common import (
WeekDay,
assert_is_on_offset,
@@ -295,15 +296,18 @@ def test_apply(self):
class TestFY5253LastOfMonthQuarter:
def test_is_anchored(self):
- assert makeFY5253LastOfMonthQuarter(
- startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4
- ).is_anchored()
- assert makeFY5253LastOfMonthQuarter(
- weekday=WeekDay.SAT, startingMonth=3, qtr_with_extra_week=4
- ).is_anchored()
- assert not makeFY5253LastOfMonthQuarter(
- 2, startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4
- ).is_anchored()
+ msg = "FY5253Quarter.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert makeFY5253LastOfMonthQuarter(
+ startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4
+ ).is_anchored()
+ assert makeFY5253LastOfMonthQuarter(
+ weekday=WeekDay.SAT, startingMonth=3, qtr_with_extra_week=4
+ ).is_anchored()
+ assert not makeFY5253LastOfMonthQuarter(
+ 2, startingMonth=1, weekday=WeekDay.SAT, qtr_with_extra_week=4
+ ).is_anchored()
def test_equality(self):
assert makeFY5253LastOfMonthQuarter(
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py
index ddf56e68b1611..62afb8b83d576 100644
--- a/pandas/tests/tseries/offsets/test_offsets.py
+++ b/pandas/tests/tseries/offsets/test_offsets.py
@@ -625,8 +625,11 @@ def test_default_constructor(self, dt):
assert (dt + DateOffset(2)) == datetime(2008, 1, 4)
def test_is_anchored(self):
- assert not DateOffset(2).is_anchored()
- assert DateOffset(1).is_anchored()
+ msg = "DateOffset.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not DateOffset(2).is_anchored()
+ assert DateOffset(1).is_anchored()
def test_copy(self):
assert DateOffset(months=2).copy() == DateOffset(months=2)
diff --git a/pandas/tests/tseries/offsets/test_quarter.py b/pandas/tests/tseries/offsets/test_quarter.py
index d183645da507d..5fd3ba0a5fb87 100644
--- a/pandas/tests/tseries/offsets/test_quarter.py
+++ b/pandas/tests/tseries/offsets/test_quarter.py
@@ -9,6 +9,7 @@
import pytest
+import pandas._testing as tm
from pandas.tests.tseries.offsets.common import (
assert_is_on_offset,
assert_offset_equal,
@@ -53,9 +54,12 @@ def test_repr(self):
assert repr(QuarterBegin(startingMonth=1)) == expected
def test_is_anchored(self):
- assert QuarterBegin(startingMonth=1).is_anchored()
- assert QuarterBegin().is_anchored()
- assert not QuarterBegin(2, startingMonth=1).is_anchored()
+ msg = "QuarterBegin.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert QuarterBegin(startingMonth=1).is_anchored()
+ assert QuarterBegin().is_anchored()
+ assert not QuarterBegin(2, startingMonth=1).is_anchored()
def test_offset_corner_case(self):
# corner
@@ -161,9 +165,12 @@ def test_repr(self):
assert repr(QuarterEnd(startingMonth=1)) == expected
def test_is_anchored(self):
- assert QuarterEnd(startingMonth=1).is_anchored()
- assert QuarterEnd().is_anchored()
- assert not QuarterEnd(2, startingMonth=1).is_anchored()
+ msg = "QuarterEnd.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert QuarterEnd(startingMonth=1).is_anchored()
+ assert QuarterEnd().is_anchored()
+ assert not QuarterEnd(2, startingMonth=1).is_anchored()
def test_offset_corner_case(self):
# corner
diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py
index b68b91826bc6f..399b7038d3426 100644
--- a/pandas/tests/tseries/offsets/test_ticks.py
+++ b/pandas/tests/tseries/offsets/test_ticks.py
@@ -339,7 +339,10 @@ def test_tick_equalities(cls):
@pytest.mark.parametrize("cls", tick_classes)
def test_tick_offset(cls):
- assert not cls().is_anchored()
+ msg = f"{cls.__name__}.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert not cls().is_anchored()
@pytest.mark.parametrize("cls", tick_classes)
diff --git a/pandas/tests/tseries/offsets/test_week.py b/pandas/tests/tseries/offsets/test_week.py
index f42ff091af277..0cd6f769769ae 100644
--- a/pandas/tests/tseries/offsets/test_week.py
+++ b/pandas/tests/tseries/offsets/test_week.py
@@ -21,6 +21,7 @@
WeekOfMonth,
)
+import pandas._testing as tm
from pandas.tests.tseries.offsets.common import (
WeekDay,
assert_is_on_offset,
@@ -42,10 +43,13 @@ def test_corner(self):
Week(weekday=-1)
def test_is_anchored(self):
- assert Week(weekday=0).is_anchored()
- assert not Week().is_anchored()
- assert not Week(2, weekday=2).is_anchored()
- assert not Week(2).is_anchored()
+ msg = "Week.is_anchored is deprecated "
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert Week(weekday=0).is_anchored()
+ assert not Week().is_anchored()
+ assert not Week(2, weekday=2).is_anchored()
+ assert not Week(2).is_anchored()
offset_cases = []
# not business week
| - [x] closes #55388
deprecated the method `is_anchored()` for offsets classes: `Tick, Week, QuarterOffset, FY5253Mixin, BaseOffset` | https://api.github.com/repos/pandas-dev/pandas/pulls/56594 | 2023-12-21T22:55:53Z | 2024-01-10T16:39:02Z | 2024-01-10T16:39:02Z | 2024-01-12T17:16:41Z |
DOC: Move deprecation note | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 535704a27169c..d1481639ca5a0 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -571,6 +571,9 @@ These methods are:
- :meth:`DataFrame.fillna`, :meth:`Series.fillna`
- :meth:`DataFrame.ffill`, :meth:`Series.ffill`
- :meth:`DataFrame.bfill`, :meth:`Series.bfill`
+- :meth:`DataFrame.mask`, :meth:`Series.mask`
+- :meth:`DataFrame.where`, :meth:`Series.where`
+- :meth:`DataFrame.clip`, :meth:`Series.clip`
Explicitly call :meth:`DataFrame.infer_objects` to replicate the current behavior in the future.
@@ -578,6 +581,8 @@ Explicitly call :meth:`DataFrame.infer_objects` to replicate the current behavio
result = result.infer_objects(copy=False)
+Or explicitly cast all-round floats to ints using ``astype``.
+
Set the following option to opt into the future behavior:
.. code-block:: ipython
@@ -618,7 +623,6 @@ Other Deprecations
- Deprecated allowing passing :class:`BlockManager` objects to :class:`DataFrame` or :class:`SingleBlockManager` objects to :class:`Series` (:issue:`52419`)
- Deprecated behavior of :meth:`Index.insert` with an object-dtype index silently performing type inference on the result, explicitly call ``result.infer_objects(copy=False)`` for the old behavior instead (:issue:`51363`)
- Deprecated casting non-datetimelike values (mainly strings) in :meth:`Series.isin` and :meth:`Index.isin` with ``datetime64``, ``timedelta64``, and :class:`PeriodDtype` dtypes (:issue:`53111`)
-- Deprecated downcasting behavior in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, :meth:`DataFrame.mask`, :meth:`Series.clip`, :meth:`DataFrame.clip`; in a future version these will not infer object-dtype columns to non-object dtype, or all-round floats to integer dtype. Call ``result.infer_objects(copy=False)`` on the result for object inference, or explicitly cast floats to ints. To opt in to the future version, use ``pd.set_option("future.no_silent_downcasting", True)`` (:issue:`53656`)
- Deprecated dtype inference in :class:`Index`, :class:`Series` and :class:`DataFrame` constructors when giving a pandas input, call ``.infer_objects`` on the input to keep the current behavior (:issue:`56012`)
- Deprecated dtype inference when setting a :class:`Index` into a :class:`DataFrame`, cast explicitly instead (:issue:`56102`)
- Deprecated including the groups in computations when using :meth:`.DataFrameGroupBy.apply` and :meth:`.DataFrameGroupBy.resample`; pass ``include_groups=False`` to exclude the groups (:issue:`7155`)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
just a reordering, not critical for the rc | https://api.github.com/repos/pandas-dev/pandas/pulls/56593 | 2023-12-21T21:43:08Z | 2023-12-22T00:07:36Z | 2023-12-22T00:07:36Z | 2023-12-22T00:07:43Z |
BLD: Add wheel builds for musllinux on aarch64 | diff --git a/.circleci/config.yml b/.circleci/config.yml
index 1c70debca0caf..90afb1ce29684 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -18,6 +18,29 @@ jobs:
PATH=$HOME/miniconda3/envs/pandas-dev/bin:$HOME/miniconda3/condabin:$PATH
LD_PRELOAD=$HOME/miniconda3/envs/pandas-dev/lib/libgomp.so.1:$LD_PRELOAD
ci/run_tests.sh
+ linux-musl:
+ docker:
+ - image: quay.io/pypa/musllinux_1_1_aarch64
+ resource_class: arm.large
+ steps:
+ # Install pkgs first to have git in the image
+ # (needed for checkout)
+ - run: |
+ apk update
+ apk add git
+ apk add musl-locales
+ - checkout
+ - run: |
+ /opt/python/cp311-cp311/bin/python -m venv ~/virtualenvs/pandas-dev
+ . ~/virtualenvs/pandas-dev/bin/activate
+ python -m pip install --no-cache-dir -U pip wheel setuptools meson-python==0.13.1 meson[ninja]==1.2.1
+ python -m pip install --no-cache-dir versioneer[toml] cython numpy python-dateutil pytz pytest>=7.3.2 pytest-xdist>=2.2.0 hypothesis>=6.46.1
+ python -m pip install --no-cache-dir --no-build-isolation -e . --config-settings=setup-args="--werror"
+ python -m pip list --no-cache-dir
+ - run: |
+ . ~/virtualenvs/pandas-dev/bin/activate
+ export PANDAS_CI=1
+ python -m pytest -m 'not slow and not network and not clipboard and not single_cpu' pandas --junitxml=test-data.xml
build-aarch64:
parameters:
cibw-build:
@@ -89,6 +112,13 @@ workflows:
equal: [ scheduled_pipeline, << pipeline.trigger_source >> ]
jobs:
- test-arm
+ test-musl:
+ # Don't run trigger this one when scheduled pipeline runs
+ when:
+ not:
+ equal: [ scheduled_pipeline, << pipeline.trigger_source >> ]
+ jobs:
+ - linux-musl
build-wheels:
jobs:
- build-aarch64:
@@ -97,4 +127,11 @@ workflows:
only: /^v.*/
matrix:
parameters:
- cibw-build: ["cp39-manylinux_aarch64", "cp310-manylinux_aarch64", "cp311-manylinux_aarch64", "cp312-manylinux_aarch64"]
+ cibw-build: ["cp39-manylinux_aarch64",
+ "cp310-manylinux_aarch64",
+ "cp311-manylinux_aarch64",
+ "cp312-manylinux_aarch64",
+ "cp39-musllinux_aarch64",
+ "cp310-musllinux_aarch64",
+ "cp311-musllinux_aarch64",
+ "cp312-musllinux_aarch64",]
diff --git a/pyproject.toml b/pyproject.toml
index f6ba25f448540..94213b0d350c9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -152,7 +152,7 @@ parentdir_prefix = "pandas-"
setup = ['--vsenv'] # For Windows
[tool.cibuildwheel]
-skip = "cp36-* cp37-* cp38-* pp* *_i686 *_ppc64le *_s390x *-musllinux_aarch64"
+skip = "cp36-* cp37-* cp38-* pp* *_i686 *_ppc64le *_s390x"
build-verbosity = "3"
environment = {LDFLAGS="-Wl,--strip-all"}
test-requires = "hypothesis>=6.46.1 pytest>=7.3.2 pytest-xdist>=2.2.0"
| - [ ] closes #55645 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56590 | 2023-12-21T19:53:36Z | 2023-12-22T15:24:08Z | 2023-12-22T15:24:08Z | 2023-12-22T15:24:10Z |
ENH: Update CFF with publication reference, Zenodo DOI, and other details | diff --git a/CITATION.cff b/CITATION.cff
index 741e7e7ac8c85..11f45b0d87ec7 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -3,12 +3,50 @@ title: 'pandas-dev/pandas: Pandas'
message: 'If you use this software, please cite it as below.'
authors:
- name: "The pandas development team"
+ website: "https://pandas.pydata.org/about/team.html"
abstract: "Pandas is a powerful data structures for data analysis, time series, and statistics."
+doi: 10.5281/zenodo.3509134
license: BSD-3-Clause
license-url: "https://github.com/pandas-dev/pandas/blob/main/LICENSE"
repository-code: "https://github.com/pandas-dev/pandas"
keywords:
- python
- data science
+ - flexible
+ - pandas
+ - alignment
+ - data analysis
type: software
-url: "https://github.com/pandas-dev/pandas"
+url: "https://pandas.pydata.org/"
+references:
+ - type: article
+ authors:
+ - given-names: Wes
+ family-names: McKinney
+ affiliation: AQR Capital Management, LLC
+ email: wesmckinn@gmail.com
+ title: Data Structures for Statistical Computing in Python
+ doi: 10.25080/Majora-92bf1922-00a
+ license: CC-BY-3.0
+ start: 56
+ end: 61
+ year: 2010
+ collection-title: Proceedings of the 9th Python in Science Conference
+ collection-doi: 10.25080/Majora-92bf1922-012
+ collection-type: proceedings
+ editors:
+ - given-names: Stéfan
+ name-particle: van der
+ family-names: Walt
+ - given-names: Jarrod
+ family-names: Millman
+ conference:
+ name: 9th Python in Science Conference (SciPy 2010)
+ city: Austin, TX
+ country: US
+ date-start: "2010-06-28"
+ date-end: "2010-07-03"
+ keywords:
+ - data structure
+ - statistics
+ - R
| Continuing in the spirit of #54241, this PR adds some further information to the CITATION.cff file, including a reference to [McKinney (2010)](https://doi.org/10.25080/Majora-92bf1922-00a), the DOI of the software itself ([10.5281/zenodo.3509134](https://doi.org/10.5281/zenodo.3509134)), a link to the [team page](https://pandas.pydata.org/about/team.html) on pandas' website, and a couple more keywords that bring this list into alignment with what the GitHub repository displays. | https://api.github.com/repos/pandas-dev/pandas/pulls/56589 | 2023-12-21T18:23:17Z | 2023-12-27T18:59:53Z | 2023-12-27T18:59:53Z | 2023-12-27T19:13:44Z |
ENH: support the Arrow PyCapsule Interface on pandas.DataFrame (export) | diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 3cdeae52a25ba..064ae473652d2 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -147,9 +147,8 @@ def import_optional_dependency(
The imported module, when found and the version is correct.
None is returned when the package is not found and `errors`
is False, or when the package's version is too old and `errors`
- is ``'warn'``.
+ is ``'warn'`` or ``'ignore'``.
"""
-
assert errors in {"warn", "raise", "ignore"}
package_name = INSTALL_MAPPING.get(name)
@@ -190,5 +189,7 @@ def import_optional_dependency(
return None
elif errors == "raise":
raise ImportError(msg)
+ else:
+ return None
return module
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index e6d86cba0a4c3..e093d551f3ead 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -988,6 +988,33 @@ def __dataframe_consortium_standard__(
)
return convert_to_standard_compliant_dataframe(self, api_version=api_version)
+ def __arrow_c_stream__(self, requested_schema=None):
+ """
+ Export the pandas DataFrame as an Arrow C stream PyCapsule.
+
+ This relies on pyarrow to convert the pandas DataFrame to the Arrow
+ format (and follows the default behaviour of ``pyarrow.Table.from_pandas``
+ in its handling of the index, i.e. store the index as a column except
+ for RangeIndex).
+ This conversion is not necessarily zero-copy.
+
+ Parameters
+ ----------
+ requested_schema : PyCapsule, default None
+ The schema to which the dataframe should be casted, passed as a
+ PyCapsule containing a C ArrowSchema representation of the
+ requested schema.
+
+ Returns
+ -------
+ PyCapsule
+ """
+ pa = import_optional_dependency("pyarrow", min_version="14.0.0")
+ if requested_schema is not None:
+ requested_schema = pa.Schema._import_from_c_capsule(requested_schema)
+ table = pa.Table.from_pandas(self, schema=requested_schema)
+ return table.__arrow_c_stream__()
+
# ----------------------------------------------------------------------
@property
diff --git a/pandas/tests/frame/test_arrow_interface.py b/pandas/tests/frame/test_arrow_interface.py
new file mode 100644
index 0000000000000..ac7b51cbdfa92
--- /dev/null
+++ b/pandas/tests/frame/test_arrow_interface.py
@@ -0,0 +1,45 @@
+import ctypes
+
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+
+pa = pytest.importorskip("pyarrow")
+
+
+@td.skip_if_no("pyarrow", min_version="14.0")
+def test_dataframe_arrow_interface():
+ df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]})
+
+ capsule = df.__arrow_c_stream__()
+ assert (
+ ctypes.pythonapi.PyCapsule_IsValid(
+ ctypes.py_object(capsule), b"arrow_array_stream"
+ )
+ == 1
+ )
+
+ table = pa.table(df)
+ expected = pa.table({"a": [1, 2, 3], "b": ["a", "b", "c"]})
+ assert table.equals(expected)
+
+ schema = pa.schema([("a", pa.int8()), ("b", pa.string())])
+ table = pa.table(df, schema=schema)
+ expected = expected.cast(schema)
+ assert table.equals(expected)
+
+
+@td.skip_if_no("pyarrow", min_version="15.0")
+def test_dataframe_to_arrow():
+ df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]})
+
+ table = pa.RecordBatchReader.from_stream(df)
+ expected = pa.table({"a": [1, 2, 3], "b": ["a", "b", "c"]})
+ assert table.equals(expected)
+
+ schema = pa.schema([("a", pa.int8()), ("b", pa.string())])
+ table = pa.RecordBatchReader.from_stream(df, schema=schema)
+ expected = expected.cast(schema)
+ assert table.equals(expected)
diff --git a/pandas/tests/test_optional_dependency.py b/pandas/tests/test_optional_dependency.py
index c1d1948d6c31a..52b5f636b1254 100644
--- a/pandas/tests/test_optional_dependency.py
+++ b/pandas/tests/test_optional_dependency.py
@@ -50,6 +50,20 @@ def test_bad_version(monkeypatch):
result = import_optional_dependency("fakemodule")
assert result is module
+ with pytest.raises(ImportError, match="Pandas requires version '1.1.0'"):
+ import_optional_dependency("fakemodule", min_version="1.1.0")
+
+ with tm.assert_produces_warning(UserWarning):
+ result = import_optional_dependency(
+ "fakemodule", errors="warn", min_version="1.1.0"
+ )
+ assert result is None
+
+ result = import_optional_dependency(
+ "fakemodule", errors="ignore", min_version="1.1.0"
+ )
+ assert result is None
+
def test_submodule(monkeypatch):
# Create a fake module with a submodule
| See https://github.com/apache/arrow/issues/39195 for some context, and https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html for the new Arrow specification.
For now this PR just implements the stream support on DataFrame (using pyarrow under the hood to do the actual conversion). We should also consider adding the array and schema protocol methods.
We could add similar methods on Series, but that has less of an exact equivalent in Arrow terms (e.g. it would loose the index).
This PR also only implements exporting a pandas DataFrame through the protocol, not adding support to our constructors to consume (import) any object supporting the protocol. | https://api.github.com/repos/pandas-dev/pandas/pulls/56587 | 2023-12-21T16:38:04Z | 2024-01-18T19:23:06Z | 2024-01-18T19:23:06Z | 2024-01-18T22:10:13Z |
BUG: convert_dtypes raising when preserving object dtype | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 1af2d9e739038..20eff9315bc80 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -746,7 +746,7 @@ def astype(
Block
"""
values = self.values
- if squeeze and values.ndim == 2:
+ if squeeze and values.ndim == 2 and is_1d_only_ea_dtype(dtype):
if values.shape[0] != 1:
raise ValueError("Can not squeeze with more than one column.")
values = values[0, :] # type: ignore[call-overload]
diff --git a/pandas/tests/frame/methods/test_convert_dtypes.py b/pandas/tests/frame/methods/test_convert_dtypes.py
index a181a271181ca..521d2cb14ac6a 100644
--- a/pandas/tests/frame/methods/test_convert_dtypes.py
+++ b/pandas/tests/frame/methods/test_convert_dtypes.py
@@ -193,3 +193,10 @@ def test_convert_dtypes_avoid_block_splitting(self):
)
tm.assert_frame_equal(result, expected)
assert result._mgr.nblocks == 2
+
+ def test_convert_dtypes_from_arrow(self):
+ # GH#56581
+ df = pd.DataFrame([["a", datetime.time(18, 12)]], columns=["a", "b"])
+ result = df.convert_dtypes()
+ expected = df.astype({"a": "string[python]"})
+ tm.assert_frame_equal(result, expected)
| - [ ] closes #56581 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/56585 | 2023-12-21T00:27:13Z | 2023-12-21T01:30:49Z | 2023-12-21T01:30:49Z | 2023-12-21T01:34:31Z |
CI: Disable linkecheck | diff --git a/.github/workflows/broken-linkcheck.yml b/.github/workflows/broken-linkcheck.yml
index 10ab5b08a4437..191252cccf1c3 100644
--- a/.github/workflows/broken-linkcheck.yml
+++ b/.github/workflows/broken-linkcheck.yml
@@ -9,6 +9,7 @@ on:
- "doc/make.py"
jobs:
linkcheck:
+ if: false
runs-on: ubuntu-latest
defaults:
run:
| Since this job is not fully ready yet, going to disable as it can "fail" if the right files were modified | https://api.github.com/repos/pandas-dev/pandas/pulls/56584 | 2023-12-20T23:51:40Z | 2023-12-21T01:32:18Z | 2023-12-21T01:32:18Z | 2023-12-21T01:32:21Z |
TST/CLN: Reuse top level fixtures instead of parametrizations | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 046cda259eefd..c325a268fe418 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -281,17 +281,6 @@ def axis(request):
return request.param
-axis_frame = axis
-
-
-@pytest.fixture(params=[1, "columns"], ids=lambda x: f"axis={repr(x)}")
-def axis_1(request):
- """
- Fixture for returning aliases of axis 1 of a DataFrame.
- """
- return request.param
-
-
@pytest.fixture(params=[True, False, None])
def observed(request):
"""
@@ -313,6 +302,22 @@ def ordered(request):
return request.param
+@pytest.fixture(params=[True, False])
+def dropna(request):
+ """
+ Boolean 'dropna' parameter.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def sort(request):
+ """
+ Boolean 'sort' parameter.
+ """
+ return request.param
+
+
@pytest.fixture(params=[True, False])
def skipna(request):
"""
@@ -414,6 +419,74 @@ def nselect_method(request):
return request.param
+@pytest.fixture(params=[None, "ignore"])
+def na_action(request):
+ """
+ Fixture for 'na_action' argument in map.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def ascending(request):
+ """
+ Fixture for 'na_action' argument in sort_values/sort_index/rank.
+ """
+ return request.param
+
+
+@pytest.fixture(params=["average", "min", "max", "first", "dense"])
+def rank_method(request):
+ """
+ Fixture for 'rank' argument in rank.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def as_index(request):
+ """
+ Fixture for 'as_index' argument in groupby.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def cache(request):
+ """
+ Fixture for 'cache' argument in to_datetime.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def parallel(request):
+ """
+ Fixture for parallel keyword argument for numba.jit.
+ """
+ return request.param
+
+
+# Can parameterize nogil & nopython over True | False, but limiting per
+# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
+
+
+@pytest.fixture(params=[False])
+def nogil(request):
+ """
+ Fixture for nogil keyword argument for numba.jit.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[True])
+def nopython(request):
+ """
+ Fixture for nopython keyword argument for numba.jit.
+ """
+ return request.param
+
+
# ----------------------------------------------------------------
# Missing values & co.
# ----------------------------------------------------------------
@@ -478,10 +551,6 @@ def index_or_series(request):
return request.param
-# Generate cartesian product of index_or_series fixture:
-index_or_series2 = index_or_series
-
-
@pytest.fixture(params=[Index, Series, pd.array], ids=["index", "series", "array"])
def index_or_series_or_array(request):
"""
@@ -674,10 +743,6 @@ def index(request):
return indices_dict[request.param].copy()
-# Needed to generate cartesian product of indices
-index_fixture2 = index
-
-
@pytest.fixture(
params=[
key for key, value in indices_dict.items() if not isinstance(value, MultiIndex)
@@ -691,10 +756,6 @@ def index_flat(request):
return indices_dict[key].copy()
-# Alias so we can test with cartesian product of index_flat
-index_flat2 = index_flat
-
-
@pytest.fixture(
params=[
key
diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py
index 17e8322dc40e1..e9967b75becce 100644
--- a/pandas/tests/apply/test_str.py
+++ b/pandas/tests/apply/test_str.py
@@ -43,10 +43,9 @@ def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("arg", ["sum", "mean", "min", "max", "std"])
-def test_with_string_args(datetime_series, arg):
- result = datetime_series.apply(arg)
- expected = getattr(datetime_series, arg)()
+def test_with_string_args(datetime_series, all_numeric_reductions):
+ result = datetime_series.apply(all_numeric_reductions)
+ expected = getattr(datetime_series, all_numeric_reductions)()
assert result == expected
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index dbff88dc6f4f6..b4e8d09c18163 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1221,7 +1221,6 @@ class TestDatetime64DateOffsetArithmetic:
# Tick DateOffsets
# TODO: parametrize over timezone?
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_dt64arr_series_add_tick_DateOffset(self, box_with_array, unit):
# GH#4532
# operate with pd.offsets
@@ -1311,7 +1310,6 @@ def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array):
# -------------------------------------------------------------
# RelativeDelta DateOffsets
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit):
# GH#10699
vec = DatetimeIndex(
@@ -1422,7 +1420,6 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit):
)
@pytest.mark.parametrize("normalize", [True, False])
@pytest.mark.parametrize("n", [0, 5])
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
@pytest.mark.parametrize("tz", [None, "US/Central"])
def test_dt64arr_add_sub_DateOffsets(
self, box_with_array, n, normalize, cls_and_kwargs, unit, tz
@@ -2356,7 +2353,6 @@ def test_dti_addsub_object_arraylike(
@pytest.mark.parametrize("years", [-1, 0, 1])
@pytest.mark.parametrize("months", [-2, 0, 2])
-@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_shift_months(years, months, unit):
dti = DatetimeIndex(
[
diff --git a/pandas/tests/arrays/boolean/test_reduction.py b/pandas/tests/arrays/boolean/test_reduction.py
index dd8c3eda9ed05..7071c6f8844e4 100644
--- a/pandas/tests/arrays/boolean/test_reduction.py
+++ b/pandas/tests/arrays/boolean/test_reduction.py
@@ -43,7 +43,6 @@ def test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip):
assert np.all(a.all()) is exp_all
-@pytest.mark.parametrize("dropna", [True, False])
def test_reductions_return_types(dropna, data, all_numeric_reductions):
op = all_numeric_reductions
s = pd.Series(data)
diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py
index d4c19a4970135..69c3364c7e98e 100644
--- a/pandas/tests/arrays/categorical/test_algos.py
+++ b/pandas/tests/arrays/categorical/test_algos.py
@@ -5,7 +5,6 @@
import pandas._testing as tm
-@pytest.mark.parametrize("ordered", [True, False])
@pytest.mark.parametrize("categories", [["b", "a", "c"], ["a", "b", "c", "d"]])
def test_factorize(categories, ordered):
cat = pd.Categorical(
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index c2c53fbc4637e..1021b18f4ae71 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -97,7 +97,6 @@ def test_min_max_ordered_empty(self, categories, expected, aggregation):
"values, categories",
[(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])],
)
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("function", ["min", "max"])
def test_min_max_with_nan(self, values, categories, function, skipna):
# GH 25303
@@ -111,7 +110,6 @@ def test_min_max_with_nan(self, values, categories, function, skipna):
assert result == expected
@pytest.mark.parametrize("function", ["min", "max"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_min_max_only_nan(self, function, skipna):
# https://github.com/pandas-dev/pandas/issues/33450
cat = Categorical([np.nan], categories=[1, 2], ordered=True)
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index a939ee5f6f53f..41d9db7335957 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -301,7 +301,6 @@ def test_set_categories(self):
(["a", "b", "c"], ["a", "b"], ["d", "e"]),
],
)
- @pytest.mark.parametrize("ordered", [True, False])
def test_set_categories_many(self, values, categories, new_categories, ordered):
c = Categorical(values, categories)
expected = Categorical(values, new_categories, ordered)
diff --git a/pandas/tests/arrays/categorical/test_astype.py b/pandas/tests/arrays/categorical/test_astype.py
index a2a53af6ab1ad..7cfd8ec8dfadf 100644
--- a/pandas/tests/arrays/categorical/test_astype.py
+++ b/pandas/tests/arrays/categorical/test_astype.py
@@ -81,7 +81,6 @@ def test_astype_str_int_categories_to_nullable_float(self):
expected = array(codes, dtype="Float64") / 2
tm.assert_extension_array_equal(res, expected)
- @pytest.mark.parametrize("ordered", [True, False])
def test_astype(self, ordered):
# string
cat = Categorical(list("abbaaccc"), ordered=ordered)
@@ -108,11 +107,10 @@ def test_astype(self, ordered):
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("dtype_ordered", [True, False])
- @pytest.mark.parametrize("cat_ordered", [True, False])
- def test_astype_category(self, dtype_ordered, cat_ordered):
+ def test_astype_category(self, dtype_ordered, ordered):
# GH#10696/GH#18593
data = list("abcaacbab")
- cat = Categorical(data, categories=list("bac"), ordered=cat_ordered)
+ cat = Categorical(data, categories=list("bac"), ordered=ordered)
# standard categories
dtype = CategoricalDtype(ordered=dtype_ordered)
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 373f1c95463fc..03678fb64d3e9 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -437,7 +437,6 @@ def test_constructor_dtype_and_others_raises(self):
Categorical(["a", "b"], ordered=False, dtype=dtype)
@pytest.mark.parametrize("categories", [None, ["a", "b"], ["a", "c"]])
- @pytest.mark.parametrize("ordered", [True, False])
def test_constructor_str_category(self, categories, ordered):
result = Categorical(
["a", "b"], categories=categories, ordered=ordered, dtype="category"
@@ -683,7 +682,6 @@ def test_from_inferred_categories_coerces(self):
expected = Categorical([1, 1, 2, np.nan])
tm.assert_categorical_equal(result, expected)
- @pytest.mark.parametrize("ordered", [None, True, False])
def test_construction_with_ordered(self, ordered):
# GH 9347, 9190
cat = Categorical([0, 1, 2], ordered=ordered)
diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py
index 525663cad1745..f2f2851c22794 100644
--- a/pandas/tests/arrays/categorical/test_dtypes.py
+++ b/pandas/tests/arrays/categorical/test_dtypes.py
@@ -83,7 +83,6 @@ def test_set_dtype_new_categories(self):
(["a", "b", "c"], ["a", "b"], ["d", "e"]),
],
)
- @pytest.mark.parametrize("ordered", [True, False])
def test_set_dtype_many(self, values, categories, new_categories, ordered):
c = Categorical(values, categories)
expected = Categorical(values, new_categories, ordered)
diff --git a/pandas/tests/arrays/categorical/test_map.py b/pandas/tests/arrays/categorical/test_map.py
index 3d41b7cc7094d..763ca9180e53a 100644
--- a/pandas/tests/arrays/categorical/test_map.py
+++ b/pandas/tests/arrays/categorical/test_map.py
@@ -10,11 +10,6 @@
import pandas._testing as tm
-@pytest.fixture(params=[None, "ignore"])
-def na_action(request):
- return request.param
-
-
@pytest.mark.parametrize(
"data, categories",
[
diff --git a/pandas/tests/arrays/datetimes/test_constructors.py b/pandas/tests/arrays/datetimes/test_constructors.py
index daf4aa3b47f56..e14cd0c6f2b7d 100644
--- a/pandas/tests/arrays/datetimes/test_constructors.py
+++ b/pandas/tests/arrays/datetimes/test_constructors.py
@@ -165,7 +165,6 @@ def test_copy(self):
arr = DatetimeArray._from_sequence(data, copy=True)
assert arr._ndarray is not data
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_numpy_datetime_unit(self, unit):
data = np.array([1, 2, 3], dtype=f"M8[{unit}]")
arr = DatetimeArray._from_sequence(data)
diff --git a/pandas/tests/arrays/datetimes/test_reductions.py b/pandas/tests/arrays/datetimes/test_reductions.py
index a941546b13a56..a58b0f57bf0da 100644
--- a/pandas/tests/arrays/datetimes/test_reductions.py
+++ b/pandas/tests/arrays/datetimes/test_reductions.py
@@ -10,10 +10,6 @@
class TestReductions:
- @pytest.fixture(params=["s", "ms", "us", "ns"])
- def unit(self, request):
- return request.param
-
@pytest.fixture
def arr1d(self, tz_naive_fixture):
"""Fixture returning DatetimeArray with parametrized timezones"""
@@ -54,7 +50,6 @@ def test_min_max(self, arr1d, unit):
assert result is NaT
@pytest.mark.parametrize("tz", [None, "US/Central"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_min_max_empty(self, skipna, tz):
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
arr = DatetimeArray._from_sequence([], dtype=dtype)
@@ -65,7 +60,6 @@ def test_min_max_empty(self, skipna, tz):
assert result is NaT
@pytest.mark.parametrize("tz", [None, "US/Central"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_median_empty(self, skipna, tz):
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
arr = DatetimeArray._from_sequence([], dtype=dtype)
@@ -164,7 +158,6 @@ def test_mean_2d(self):
expected = dti.mean()
assert result == expected
- @pytest.mark.parametrize("skipna", [True, False])
def test_mean_empty(self, arr1d, skipna):
arr = arr1d[:0]
diff --git a/pandas/tests/arrays/floating/test_function.py b/pandas/tests/arrays/floating/test_function.py
index 40fd66fd049a6..9ea48bfb2413f 100644
--- a/pandas/tests/arrays/floating/test_function.py
+++ b/pandas/tests/arrays/floating/test_function.py
@@ -127,7 +127,6 @@ def test_value_counts_with_normalize():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("min_count", [0, 4])
def test_floating_array_sum(skipna, min_count, dtype):
arr = pd.array([1, 2, 3, None], dtype=dtype)
@@ -171,7 +170,6 @@ def test_preserve_dtypes(op):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("method", ["min", "max"])
def test_floating_array_min_max(skipna, method, dtype):
arr = pd.array([0.0, 1.0, None], dtype=dtype)
@@ -183,7 +181,6 @@ def test_floating_array_min_max(skipna, method, dtype):
assert result is pd.NA
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("min_count", [0, 9])
def test_floating_array_prod(skipna, min_count, dtype):
arr = pd.array([1.0, 2.0, None], dtype=dtype)
diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py
index e3848cdfe3aa9..99db05229a57d 100644
--- a/pandas/tests/arrays/integer/test_dtypes.py
+++ b/pandas/tests/arrays/integer/test_dtypes.py
@@ -59,7 +59,6 @@ def test_astype_nansafe():
arr.astype("uint32")
-@pytest.mark.parametrize("dropna", [True, False])
def test_construct_index(all_data, dropna):
# ensure that we do not coerce to different Index dtype or non-index
@@ -76,7 +75,6 @@ def test_construct_index(all_data, dropna):
tm.assert_index_equal(result, expected)
-@pytest.mark.parametrize("dropna", [True, False])
def test_astype_index(all_data, dropna):
# as an int/uint index to Index
diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py
index d48b636a98feb..33300fff925f6 100644
--- a/pandas/tests/arrays/integer/test_function.py
+++ b/pandas/tests/arrays/integer/test_function.py
@@ -141,7 +141,6 @@ def test_value_counts_with_normalize():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("min_count", [0, 4])
def test_integer_array_sum(skipna, min_count, any_int_ea_dtype):
dtype = any_int_ea_dtype
@@ -153,7 +152,6 @@ def test_integer_array_sum(skipna, min_count, any_int_ea_dtype):
assert result is pd.NA
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("method", ["min", "max"])
def test_integer_array_min_max(skipna, method, any_int_ea_dtype):
dtype = any_int_ea_dtype
@@ -166,7 +164,6 @@ def test_integer_array_min_max(skipna, method, any_int_ea_dtype):
assert result is pd.NA
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("min_count", [0, 9])
def test_integer_array_prod(skipna, min_count, any_int_ea_dtype):
dtype = any_int_ea_dtype
diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
index be4b2c3e7e74c..58ba340441d86 100644
--- a/pandas/tests/arrays/interval/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -58,12 +58,11 @@ def test_is_empty(self, constructor, left, right, closed):
class TestMethods:
- @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
- def test_set_closed(self, closed, new_closed):
+ def test_set_closed(self, closed, other_closed):
# GH 21670
array = IntervalArray.from_breaks(range(10), closed=closed)
- result = array.set_closed(new_closed)
- expected = IntervalArray.from_breaks(range(10), closed=new_closed)
+ result = array.set_closed(other_closed)
+ expected = IntervalArray.from_breaks(range(10), closed=other_closed)
tm.assert_extension_array_equal(result, expected)
@pytest.mark.parametrize(
diff --git a/pandas/tests/arrays/period/test_reductions.py b/pandas/tests/arrays/period/test_reductions.py
index 2889cc786dd71..5b859d86eb6d0 100644
--- a/pandas/tests/arrays/period/test_reductions.py
+++ b/pandas/tests/arrays/period/test_reductions.py
@@ -1,5 +1,3 @@
-import pytest
-
import pandas as pd
from pandas.core.arrays import period_array
@@ -32,7 +30,6 @@ def test_min_max(self):
result = arr.max(skipna=False)
assert result is pd.NaT
- @pytest.mark.parametrize("skipna", [True, False])
def test_min_max_empty(self, skipna):
arr = period_array([], freq="D")
result = arr.min(skipna=skipna)
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 320bdca60a932..f67268616a021 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -415,7 +415,6 @@ def test_astype_float(dtype, any_float_dtype):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce(skipna, dtype):
arr = pd.Series(["a", "b", "c"], dtype=dtype)
@@ -423,7 +422,6 @@ def test_reduce(skipna, dtype):
assert result == "abc"
-@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce_missing(skipna, dtype):
arr = pd.Series([None, "a", None, "b", "c", None], dtype=dtype)
@@ -435,7 +433,6 @@ def test_reduce_missing(skipna, dtype):
@pytest.mark.parametrize("method", ["min", "max"])
-@pytest.mark.parametrize("skipna", [True, False])
def test_min_max(method, skipna, dtype):
arr = pd.Series(["a", "b", "c", None], dtype=dtype)
result = getattr(arr, method)(skipna=skipna)
diff --git a/pandas/tests/arrays/timedeltas/test_reductions.py b/pandas/tests/arrays/timedeltas/test_reductions.py
index 991dbf41c8087..3565f2e8690e2 100644
--- a/pandas/tests/arrays/timedeltas/test_reductions.py
+++ b/pandas/tests/arrays/timedeltas/test_reductions.py
@@ -10,7 +10,6 @@
class TestReductions:
@pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_reductions_empty(self, name, skipna):
tdi = pd.TimedeltaIndex([])
arr = tdi.array
@@ -21,7 +20,6 @@ def test_reductions_empty(self, name, skipna):
result = getattr(arr, name)(skipna=skipna)
assert result is pd.NaT
- @pytest.mark.parametrize("skipna", [True, False])
def test_sum_empty(self, skipna):
tdi = pd.TimedeltaIndex([])
arr = tdi.array
diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py
index d3fe144f70cfc..3a8ed471f9dc0 100644
--- a/pandas/tests/base/test_unique.py
+++ b/pandas/tests/base/test_unique.py
@@ -116,7 +116,6 @@ def test_unique_bad_unicode(index_or_series):
tm.assert_numpy_array_equal(result, expected)
-@pytest.mark.parametrize("dropna", [True, False])
def test_nunique_dropna(dropna):
# GH37566
ser = pd.Series(["yes", "yes", pd.NA, np.nan, None, pd.NaT])
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
index 2729666398877..a0b0bdfdb46d8 100644
--- a/pandas/tests/base/test_value_counts.py
+++ b/pandas/tests/base/test_value_counts.py
@@ -329,7 +329,6 @@ def test_value_counts_timedelta64(index_or_series, unit):
tm.assert_series_equal(result2, expected_s)
-@pytest.mark.parametrize("dropna", [True, False])
def test_value_counts_with_nan(dropna, index_or_series):
# GH31944
klass = index_or_series
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 0dad0b05303ad..c52d49034f74e 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -959,25 +959,24 @@ def test_same_categories_different_order(self):
c2 = CategoricalDtype(["b", "a"], ordered=True)
assert c1 is not c2
- @pytest.mark.parametrize("ordered1", [True, False, None])
@pytest.mark.parametrize("ordered2", [True, False, None])
- def test_categorical_equality(self, ordered1, ordered2):
+ def test_categorical_equality(self, ordered, ordered2):
# same categories, same order
# any combination of None/False are equal
# True/True is the only combination with True that are equal
- c1 = CategoricalDtype(list("abc"), ordered1)
+ c1 = CategoricalDtype(list("abc"), ordered)
c2 = CategoricalDtype(list("abc"), ordered2)
result = c1 == c2
- expected = bool(ordered1) is bool(ordered2)
+ expected = bool(ordered) is bool(ordered2)
assert result is expected
# same categories, different order
# any combination of None/False are equal (order doesn't matter)
# any combination with True are not equal (different order of cats)
- c1 = CategoricalDtype(list("abc"), ordered1)
+ c1 = CategoricalDtype(list("abc"), ordered)
c2 = CategoricalDtype(list("cab"), ordered2)
result = c1 == c2
- expected = (bool(ordered1) is False) and (bool(ordered2) is False)
+ expected = (bool(ordered) is False) and (bool(ordered2) is False)
assert result is expected
# different categories
@@ -985,9 +984,9 @@ def test_categorical_equality(self, ordered1, ordered2):
assert c1 != c2
# none categories
- c1 = CategoricalDtype(list("abc"), ordered1)
+ c1 = CategoricalDtype(list("abc"), ordered)
c2 = CategoricalDtype(None, ordered2)
- c3 = CategoricalDtype(None, ordered1)
+ c3 = CategoricalDtype(None, ordered)
assert c1 != c2
assert c2 != c1
assert c2 == c3
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 49eb06c299886..3ec6d70494902 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1052,7 +1052,6 @@ def test_inferred_dtype_fixture(self, any_skipna_inferred_dtype):
# make sure the inferred dtype of the fixture is as requested
assert inferred_dtype == lib.infer_dtype(values, skipna=True)
- @pytest.mark.parametrize("skipna", [True, False])
def test_length_zero(self, skipna):
result = lib.infer_dtype(np.array([], dtype="i4"), skipna=skipna)
assert result == "integer"
@@ -1164,7 +1163,6 @@ def test_decimals(self):
assert result == "decimal"
# complex is compatible with nan, so skipna has no effect
- @pytest.mark.parametrize("skipna", [True, False])
def test_complex(self, skipna):
# gets cast to complex on array construction
arr = np.array([1.0, 2.0, 1 + 1j])
@@ -1343,9 +1341,8 @@ def test_infer_dtype_period(self):
arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")])
assert lib.infer_dtype(arr, skipna=True) == "mixed"
- @pytest.mark.parametrize("klass", [pd.array, Series, Index])
- @pytest.mark.parametrize("skipna", [True, False])
- def test_infer_dtype_period_array(self, klass, skipna):
+ def test_infer_dtype_period_array(self, index_or_series_or_array, skipna):
+ klass = index_or_series_or_array
# https://github.com/pandas-dev/pandas/issues/23553
values = klass(
[
@@ -1534,7 +1531,6 @@ def test_date(self):
[pd.NaT, date(2020, 1, 1)],
],
)
- @pytest.mark.parametrize("skipna", [True, False])
def test_infer_dtype_date_order_invariant(self, values, skipna):
# https://github.com/pandas-dev/pandas/issues/33741
result = lib.infer_dtype(values, skipna=skipna)
@@ -1706,7 +1702,6 @@ def test_interval_mismatched_subtype(self):
assert lib.infer_dtype(arr, skipna=False) == "interval"
@pytest.mark.parametrize("klass", [pd.array, Series])
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("data", [["a", "b", "c"], ["a", "b", pd.NA]])
def test_string_dtype(self, data, skipna, klass, nullable_string_dtype):
# StringArray
@@ -1715,7 +1710,6 @@ def test_string_dtype(self, data, skipna, klass, nullable_string_dtype):
assert inferred == "string"
@pytest.mark.parametrize("klass", [pd.array, Series])
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("data", [[True, False, True], [True, False, pd.NA]])
def test_boolean_dtype(self, data, skipna, klass):
# BooleanArray
diff --git a/pandas/tests/extension/base/accumulate.py b/pandas/tests/extension/base/accumulate.py
index 9a41a3a582c4a..9189ef7ec9aa5 100644
--- a/pandas/tests/extension/base/accumulate.py
+++ b/pandas/tests/extension/base/accumulate.py
@@ -26,7 +26,6 @@ def check_accumulate(self, ser: pd.Series, op_name: str, skipna: bool):
expected = getattr(alt, op_name)(skipna=skipna)
tm.assert_series_equal(result, expected, check_dtype=False)
- @pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series(self, data, all_numeric_accumulations, skipna):
op_name = all_numeric_accumulations
ser = pd.Series(data)
diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py
index c7b768f6e3c88..3fb116430861a 100644
--- a/pandas/tests/extension/base/dtype.py
+++ b/pandas/tests/extension/base/dtype.py
@@ -114,7 +114,6 @@ def test_get_common_dtype(self, dtype):
# only case we can test in general)
assert dtype._get_common_dtype([dtype]) == dtype
- @pytest.mark.parametrize("skipna", [True, False])
def test_infer_dtype(self, data, data_missing, skipna):
# only testing that this works without raising an error
res = infer_dtype(data, skipna=skipna)
diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py
index 75628ea177fc2..9f38246d1a317 100644
--- a/pandas/tests/extension/base/groupby.py
+++ b/pandas/tests/extension/base/groupby.py
@@ -34,7 +34,6 @@ def test_grouping_grouper(self, data_for_grouping):
tm.assert_numpy_array_equal(gr1.grouping_vector, df.A.values)
tm.assert_extension_array_equal(gr2.grouping_vector, data_for_grouping)
- @pytest.mark.parametrize("as_index", [True, False])
def test_groupby_extension_agg(self, as_index, data_for_grouping):
df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], "B": data_for_grouping})
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py
index c803a8113b4a4..ba247f51e5f1b 100644
--- a/pandas/tests/extension/base/methods.py
+++ b/pandas/tests/extension/base/methods.py
@@ -37,7 +37,6 @@ def test_value_counts_default_dropna(self, data):
kwarg = sig.parameters["dropna"]
assert kwarg.default is True
- @pytest.mark.parametrize("dropna", [True, False])
def test_value_counts(self, all_data, dropna):
all_data = all_data[:10]
if dropna:
@@ -97,7 +96,6 @@ def test_apply_simple_series(self, data):
result = pd.Series(data).apply(id)
assert isinstance(result, pd.Series)
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action):
result = data_missing.map(lambda x: x, na_action=na_action)
expected = data_missing.to_numpy()
@@ -213,7 +211,6 @@ def test_nargsort(self, data_missing_for_sorting, na_position, expected):
result = nargsort(data_missing_for_sorting, na_position=na_position)
tm.assert_numpy_array_equal(result, expected)
- @pytest.mark.parametrize("ascending", [True, False])
def test_sort_values(self, data_for_sorting, ascending, sort_by_key):
ser = pd.Series(data_for_sorting)
result = ser.sort_values(ascending=ascending, key=sort_by_key)
@@ -227,7 +224,6 @@ def test_sort_values(self, data_for_sorting, ascending, sort_by_key):
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize("ascending", [True, False])
def test_sort_values_missing(
self, data_missing_for_sorting, ascending, sort_by_key
):
@@ -239,7 +235,6 @@ def test_sort_values_missing(
expected = ser.iloc[[0, 2, 1]]
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize("ascending", [True, False])
def test_sort_values_frame(self, data_for_sorting, ascending):
df = pd.DataFrame({"A": [1, 2, 1], "B": data_for_sorting})
result = df.sort_values(["A", "B"])
@@ -248,7 +243,6 @@ def test_sort_values_frame(self, data_for_sorting, ascending):
)
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize("keep", ["first", "last", False])
def test_duplicated(self, data, keep):
arr = data.take([0, 1, 0, 1])
result = arr.duplicated(keep=keep)
diff --git a/pandas/tests/extension/base/reduce.py b/pandas/tests/extension/base/reduce.py
index 6ea1b3a6fbe9d..2a443901fa41a 100644
--- a/pandas/tests/extension/base/reduce.py
+++ b/pandas/tests/extension/base/reduce.py
@@ -77,7 +77,6 @@ def check_reduce_frame(self, ser: pd.Series, op_name: str, skipna: bool):
tm.assert_extension_array_equal(result1, expected)
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
op_name = all_boolean_reductions
ser = pd.Series(data)
@@ -96,7 +95,6 @@ def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
self.check_reduce(ser, op_name, skipna)
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
op_name = all_numeric_reductions
ser = pd.Series(data)
@@ -115,7 +113,6 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
# min/max with empty produce numpy warnings
self.check_reduce(ser, op_name, skipna)
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna):
op_name = all_numeric_reductions
ser = pd.Series(data)
diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py
index 9dd0a2eba6c0d..4a2942776b25e 100644
--- a/pandas/tests/extension/base/setitem.py
+++ b/pandas/tests/extension/base/setitem.py
@@ -105,10 +105,9 @@ def test_setitem_sequence_broadcasts(self, data, box_in_series):
assert data[0] == data[2]
assert data[1] == data[2]
- @pytest.mark.parametrize("setter", ["loc", "iloc"])
- def test_setitem_scalar(self, data, setter):
+ def test_setitem_scalar(self, data, indexer_li):
arr = pd.Series(data)
- setter = getattr(arr, setter)
+ setter = indexer_li(arr)
setter[0] = data[1]
assert arr[0] == data[1]
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index b3c57ee49a724..49f29b2194cae 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -227,8 +227,7 @@ def test_fillna_copy_series(self, data_missing, using_copy_on_write):
with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
super().test_fillna_copy_series(data_missing)
- @pytest.mark.parametrize("dropna", [True, False])
- def test_value_counts(self, all_data, dropna, request):
+ def test_value_counts(self, all_data, dropna):
all_data = all_data[:10]
if dropna:
other = np.array(all_data[~all_data.isna()])
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 7686bc5abb44c..5319291f2ea01 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -162,18 +162,6 @@ def test_sort_values_frame(self):
# TODO (EA.factorize): see if _values_for_factorize allows this.
super().test_sort_values_frame()
- @pytest.mark.parametrize("ascending", [True, False])
- def test_sort_values(self, data_for_sorting, ascending, sort_by_key):
- super().test_sort_values(data_for_sorting, ascending, sort_by_key)
-
- @pytest.mark.parametrize("ascending", [True, False])
- def test_sort_values_missing(
- self, data_missing_for_sorting, ascending, sort_by_key
- ):
- super().test_sort_values_missing(
- data_missing_for_sorting, ascending, sort_by_key
- )
-
@pytest.mark.xfail(reason="combine for JSONArray not supported")
def test_combine_le(self, data_repeated):
super().test_combine_le(data_repeated)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index ed1b7b199a16f..76982ee5c38f8 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -271,7 +271,6 @@ def test_compare_scalar(self, data, comparison_op):
ser = pd.Series(data)
self._compare_other(ser, data, comparison_op, data[0])
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action):
if data_missing.dtype.kind in "mM":
result = data_missing.map(lambda x: x, na_action=na_action)
@@ -424,7 +423,6 @@ def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
return False
return True
- @pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request):
pa_type = data.dtype.pyarrow_dtype
op_name = all_numeric_accumulations
@@ -526,7 +524,6 @@ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
expected = getattr(alt, op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
dtype = data.dtype
pa_dtype = dtype.pyarrow_dtype
@@ -552,7 +549,6 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, reque
request.applymarker(xfail_mark)
super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_boolean(
self, data, all_boolean_reductions, skipna, na_value, request
):
@@ -589,7 +585,6 @@ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
}[arr.dtype.kind]
return cmp_dtype
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
op_name = all_numeric_reductions
if op_name == "skew":
@@ -2325,7 +2320,6 @@ def test_str_extract_expand():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_duration_from_strings_with_nat(unit):
# GH51175
strings = ["1000", "NaT"]
@@ -2828,7 +2822,6 @@ def test_dt_components():
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("skipna", [True, False])
def test_boolean_reduce_series_all_null(all_boolean_reductions, skipna):
# GH51624
ser = pd.Series([None], dtype="float64[pyarrow]")
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 1b322b1797144..edf560dda36e7 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -117,10 +117,6 @@ def test_getitem_scalar(self, data):
# to break things by changing.
super().test_getitem_scalar(data)
- @pytest.mark.xfail(reason="Unobserved categories included")
- def test_value_counts(self, all_data, dropna):
- return super().test_value_counts(all_data, dropna)
-
def test_combine_add(self, data_repeated):
# GH 20825
# When adding categoricals in combine, result is a string
@@ -138,7 +134,6 @@ def test_combine_add(self, data_repeated):
expected = pd.Series([a + val for a in list(orig_data1)])
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data, na_action):
result = data.map(lambda x: x, na_action=na_action)
tm.assert_extension_array_equal(result, data)
@@ -179,7 +174,6 @@ def test_array_repr(self, data, size):
super().test_array_repr(data, size)
@pytest.mark.xfail(reason="TBD")
- @pytest.mark.parametrize("as_index", [True, False])
def test_groupby_extension_agg(self, as_index, data_for_grouping):
super().test_groupby_extension_agg(as_index, data_for_grouping)
diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py
index 7f70957007dad..4b25b2768849e 100644
--- a/pandas/tests/extension/test_datetime.py
+++ b/pandas/tests/extension/test_datetime.py
@@ -24,9 +24,9 @@
from pandas.tests.extension import base
-@pytest.fixture(params=["US/Central"])
-def dtype(request):
- return DatetimeTZDtype(unit="ns", tz=request.param)
+@pytest.fixture
+def dtype():
+ return DatetimeTZDtype(unit="ns", tz="US/Central")
@pytest.fixture
@@ -100,7 +100,6 @@ def _supports_accumulation(self, ser, op_name: str) -> bool:
def _supports_reduction(self, obj, op_name: str) -> bool:
return op_name in ["min", "max", "median", "mean", "std", "any", "all"]
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
meth = all_boolean_reductions
msg = f"'{meth}' with datetime64 dtypes is deprecated and will raise in"
@@ -114,7 +113,6 @@ def test_series_constructor(self, data):
data = data._with_freq(None)
super().test_series_constructor(data)
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data, na_action):
result = data.map(lambda x: x, na_action=na_action)
tm.assert_extension_array_equal(result, data)
diff --git a/pandas/tests/extension/test_masked.py b/pandas/tests/extension/test_masked.py
index 3efc561d6a125..0e19c4078b471 100644
--- a/pandas/tests/extension/test_masked.py
+++ b/pandas/tests/extension/test_masked.py
@@ -169,7 +169,6 @@ def data_for_grouping(dtype):
class TestMaskedArrays(base.ExtensionTests):
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action):
result = data_missing.map(lambda x: x, na_action=na_action)
if data_missing.dtype == Float32Dtype():
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index aaf49f53ba02b..8bf16272dd8c5 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -313,7 +313,6 @@ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
tm.assert_almost_equal(result, expected)
@pytest.mark.skip("TODO: tests not written yet")
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna):
pass
diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py
index 2d1d213322bac..4fe9c160d66af 100644
--- a/pandas/tests/extension/test_period.py
+++ b/pandas/tests/extension/test_period.py
@@ -109,7 +109,6 @@ def test_diff(self, data, periods):
else:
super().test_diff(data, periods)
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data, na_action):
result = data.map(lambda x: x, na_action=na_action)
tm.assert_extension_array_equal(result, data)
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index 4039a5d01f372..03f179fdd261e 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -102,7 +102,6 @@ class TestSparseArray(base.ExtensionTests):
def _supports_reduction(self, obj, op_name: str) -> bool:
return True
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
if all_numeric_reductions in [
"prod",
@@ -127,7 +126,6 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, reque
super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
- @pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
if all_numeric_reductions in [
"prod",
@@ -368,7 +366,6 @@ def test_map(self, func, na_action, expected):
result = data.map(func, na_action=na_action)
tm.assert_extension_array_equal(result, expected)
- @pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_raises(self, data, na_action):
# GH52096
msg = "fill value in the sparse values not supported"
@@ -489,7 +486,6 @@ def test_array_repr(self, data, size):
super().test_array_repr(data, size)
@pytest.mark.xfail(reason="result does not match expected")
- @pytest.mark.parametrize("as_index", [True, False])
def test_groupby_extension_agg(self, as_index, data_for_grouping):
super().test_groupby_extension_agg(as_index, data_for_grouping)
diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py
index 5a9c47866dae8..1f5d960de40c1 100644
--- a/pandas/tests/frame/methods/test_align.py
+++ b/pandas/tests/frame/methods/test_align.py
@@ -395,7 +395,6 @@ def test_missing_axis_specification_exception(self):
@pytest.mark.parametrize("method", ["pad", "bfill"])
@pytest.mark.parametrize("axis", [0, 1, None])
@pytest.mark.parametrize("fill_axis", [0, 1])
- @pytest.mark.parametrize("how", ["inner", "outer", "left", "right"])
@pytest.mark.parametrize(
"left_slice",
[
@@ -412,8 +411,17 @@ def test_missing_axis_specification_exception(self):
)
@pytest.mark.parametrize("limit", [1, None])
def test_align_fill_method(
- self, how, method, axis, fill_axis, float_frame, left_slice, right_slice, limit
+ self,
+ join_type,
+ method,
+ axis,
+ fill_axis,
+ float_frame,
+ left_slice,
+ right_slice,
+ limit,
):
+ how = join_type
frame = float_frame
left = frame.iloc[left_slice[0], left_slice[1]]
right = frame.iloc[right_slice[0], right_slice[1]]
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py
index ef72ca1ac86b9..87d1745774487 100644
--- a/pandas/tests/frame/methods/test_asfreq.py
+++ b/pandas/tests/frame/methods/test_asfreq.py
@@ -19,10 +19,6 @@
class TestAsFreq:
- @pytest.fixture(params=["s", "ms", "us", "ns"])
- def unit(self, request):
- return request.param
-
def test_asfreq2(self, frame_or_series):
ts = frame_or_series(
[0.0, 1.0, 2.0],
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 5a1e3cd786f84..b73c759518b0e 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -498,11 +498,10 @@ def test_astype_to_datetime_unit(self, unit):
assert exp_dta.dtype == dtype
tm.assert_extension_array_equal(res_dta, exp_dta)
- @pytest.mark.parametrize("unit", ["ns"])
- def test_astype_to_timedelta_unit_ns(self, unit):
+ def test_astype_to_timedelta_unit_ns(self):
# preserver the timedelta conversion
# GH#19223
- dtype = f"m8[{unit}]"
+ dtype = "m8[ns]"
arr = np.array([[1, 2, 3]], dtype=dtype)
df = DataFrame(arr)
result = df.astype(dtype)
diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py
index 4c1434bd66aff..1ebe9920933d1 100644
--- a/pandas/tests/frame/methods/test_at_time.py
+++ b/pandas/tests/frame/methods/test_at_time.py
@@ -95,7 +95,6 @@ def test_at_time_raises(self, frame_or_series):
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
obj.at_time("00:00")
- @pytest.mark.parametrize("axis", ["index", "columns", 0, 1])
def test_at_time_axis(self, axis):
# issue 8839
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index 735f6c50ab739..02f0b9e20871d 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -391,8 +391,8 @@ def test_join_list_series(float_frame):
tm.assert_frame_equal(result, float_frame)
-@pytest.mark.parametrize("sort_kw", [True, False])
-def test_suppress_future_warning_with_sort_kw(sort_kw):
+def test_suppress_future_warning_with_sort_kw(sort):
+ sort_kw = sort
a = DataFrame({"col1": [1, 2]}, index=["c", "a"])
b = DataFrame({"col2": [4, 5]}, index=["b", "a"])
diff --git a/pandas/tests/frame/methods/test_map.py b/pandas/tests/frame/methods/test_map.py
index 03681c3df844e..a60dcf9a02938 100644
--- a/pandas/tests/frame/methods/test_map.py
+++ b/pandas/tests/frame/methods/test_map.py
@@ -33,7 +33,6 @@ def test_map_float_object_conversion(val):
assert result == object
-@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_keeps_dtype(na_action):
# GH52219
arr = Series(["a", np.nan, "b"])
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index 8d7a0b373f5f8..1d0931f5982b7 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -31,13 +31,6 @@ class TestRank:
"dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]),
}
- @pytest.fixture(params=["average", "min", "max", "first", "dense"])
- def method(self, request):
- """
- Fixture for trying all rank methods
- """
- return request.param
-
def test_rank(self, float_frame):
sp_stats = pytest.importorskip("scipy.stats")
@@ -225,8 +218,7 @@ def test_rank_axis(self):
tm.assert_frame_equal(df.rank(axis=1), df.rank(axis="columns"))
@pytest.mark.parametrize("ax", [0, 1])
- @pytest.mark.parametrize("m", ["average", "min", "max", "first", "dense"])
- def test_rank_methods_frame(self, ax, m):
+ def test_rank_methods_frame(self, ax, rank_method):
sp_stats = pytest.importorskip("scipy.stats")
xs = np.random.default_rng(2).integers(0, 21, (100, 26))
@@ -236,16 +228,19 @@ def test_rank_methods_frame(self, ax, m):
for vals in [xs, xs + 1e6, xs * 1e-6]:
df = DataFrame(vals, columns=cols)
- result = df.rank(axis=ax, method=m)
+ result = df.rank(axis=ax, method=rank_method)
sprank = np.apply_along_axis(
- sp_stats.rankdata, ax, vals, m if m != "first" else "ordinal"
+ sp_stats.rankdata,
+ ax,
+ vals,
+ rank_method if rank_method != "first" else "ordinal",
)
sprank = sprank.astype(np.float64)
expected = DataFrame(sprank, columns=cols).astype("float64")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("dtype", ["O", "f8", "i8"])
- def test_rank_descending(self, method, dtype):
+ def test_rank_descending(self, rank_method, dtype):
if "i" in dtype:
df = self.df.dropna().astype(dtype)
else:
@@ -255,18 +250,18 @@ def test_rank_descending(self, method, dtype):
expected = (df.max() - df).rank()
tm.assert_frame_equal(res, expected)
- expected = (df.max() - df).rank(method=method)
+ expected = (df.max() - df).rank(method=rank_method)
if dtype != "O":
- res2 = df.rank(method=method, ascending=False, numeric_only=True)
+ res2 = df.rank(method=rank_method, ascending=False, numeric_only=True)
tm.assert_frame_equal(res2, expected)
- res3 = df.rank(method=method, ascending=False, numeric_only=False)
+ res3 = df.rank(method=rank_method, ascending=False, numeric_only=False)
tm.assert_frame_equal(res3, expected)
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("dtype", [None, object])
- def test_rank_2d_tie_methods(self, method, axis, dtype):
+ def test_rank_2d_tie_methods(self, rank_method, axis, dtype):
df = self.df
def _check2d(df, expected, method="average", axis=0):
@@ -276,14 +271,14 @@ def _check2d(df, expected, method="average", axis=0):
df = df.T
exp_df = exp_df.T
- result = df.rank(method=method, axis=axis)
+ result = df.rank(method=rank_method, axis=axis)
tm.assert_frame_equal(result, exp_df)
frame = df if dtype is None else df.astype(dtype)
- _check2d(frame, self.results[method], method=method, axis=axis)
+ _check2d(frame, self.results[rank_method], method=rank_method, axis=axis)
@pytest.mark.parametrize(
- "method,exp",
+ "rank_method,exp",
[
("dense", [[1.0, 1.0, 1.0], [1.0, 0.5, 2.0 / 3], [1.0, 0.5, 1.0 / 3]]),
(
@@ -312,11 +307,11 @@ def _check2d(df, expected, method="average", axis=0):
),
],
)
- def test_rank_pct_true(self, method, exp):
+ def test_rank_pct_true(self, rank_method, exp):
# see gh-15630.
df = DataFrame([[2012, 66, 3], [2012, 65, 2], [2012, 65, 1]])
- result = df.rank(method=method, pct=True)
+ result = df.rank(method=rank_method, pct=True)
expected = DataFrame(exp)
tm.assert_frame_equal(result, expected)
@@ -454,10 +449,10 @@ def test_rank_both_inf(self):
],
)
def test_rank_inf_nans_na_option(
- self, frame_or_series, method, na_option, ascending, expected
+ self, frame_or_series, rank_method, na_option, ascending, expected
):
obj = frame_or_series([np.inf, np.nan, -np.inf])
- result = obj.rank(method=method, na_option=na_option, ascending=ascending)
+ result = obj.rank(method=rank_method, na_option=na_option, ascending=ascending)
expected = frame_or_series(expected)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py
index 49e292057e4dc..821b2e0d7a6da 100644
--- a/pandas/tests/frame/methods/test_sort_index.py
+++ b/pandas/tests/frame/methods/test_sort_index.py
@@ -927,7 +927,6 @@ def test_sort_index_na_position(self):
result = df.sort_index(level=[0, 1], na_position="last")
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize("ascending", [True, False])
def test_sort_index_multiindex_sort_remaining(self, ascending):
# GH #24247
df = DataFrame(
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index be75efcdfe9d3..b33ca95bd4180 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -848,11 +848,6 @@ def sort_names(request):
return request.param
-@pytest.fixture(params=[True, False])
-def ascending(request):
- return request.param
-
-
class TestSortValuesLevelAsStr:
def test_sort_index_level_and_column_label(
self, df_none, df_idx, sort_names, ascending, request
@@ -926,7 +921,6 @@ def test_sort_values_validate_ascending_for_value_error(self):
with pytest.raises(ValueError, match=msg):
df.sort_values(by="D", ascending="False")
- @pytest.mark.parametrize("ascending", [False, 0, 1, True])
def test_sort_values_validate_ascending_functional(self, ascending):
df = DataFrame({"D": [23, 7, 21]})
indexer = df["D"].argsort().values
diff --git a/pandas/tests/frame/test_cumulative.py b/pandas/tests/frame/test_cumulative.py
index 5bd9c42612315..d7aad680d389e 100644
--- a/pandas/tests/frame/test_cumulative.py
+++ b/pandas/tests/frame/test_cumulative.py
@@ -7,7 +7,6 @@
"""
import numpy as np
-import pytest
from pandas import (
DataFrame,
@@ -46,20 +45,23 @@ def test_cumprod_smoke(self, datetime_frame):
df.cumprod(0)
df.cumprod(1)
- @pytest.mark.parametrize("method", ["cumsum", "cumprod", "cummin", "cummax"])
- def test_cumulative_ops_match_series_apply(self, datetime_frame, method):
+ def test_cumulative_ops_match_series_apply(
+ self, datetime_frame, all_numeric_accumulations
+ ):
datetime_frame.iloc[5:10, 0] = np.nan
datetime_frame.iloc[10:15, 1] = np.nan
datetime_frame.iloc[15:, 2] = np.nan
# axis = 0
- result = getattr(datetime_frame, method)()
- expected = datetime_frame.apply(getattr(Series, method))
+ result = getattr(datetime_frame, all_numeric_accumulations)()
+ expected = datetime_frame.apply(getattr(Series, all_numeric_accumulations))
tm.assert_frame_equal(result, expected)
# axis = 1
- result = getattr(datetime_frame, method)(axis=1)
- expected = datetime_frame.apply(getattr(Series, method), axis=1)
+ result = getattr(datetime_frame, all_numeric_accumulations)(axis=1)
+ expected = datetime_frame.apply(
+ getattr(Series, all_numeric_accumulations), axis=1
+ )
tm.assert_frame_equal(result, expected)
# fix issue TODO: GH ref?
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index dd88e7401a03f..5aaa11b848be4 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1059,7 +1059,6 @@ def test_sum_bools(self):
# ----------------------------------------------------------------------
# Index of max / min
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("axis", [0, 1])
def test_idxmin(self, float_frame, int_frame, skipna, axis):
frame = float_frame
@@ -1108,7 +1107,6 @@ def test_idxmin_axis_2(self, float_frame):
with pytest.raises(ValueError, match=msg):
frame.idxmin(axis=2)
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize("axis", [0, 1])
def test_idxmax(self, float_frame, int_frame, skipna, axis):
frame = float_frame
@@ -1257,29 +1255,30 @@ def test_idxmax_dt64_multicolumn_axis1(self):
# ----------------------------------------------------------------------
# Logical reductions
- @pytest.mark.parametrize("opname", ["any", "all"])
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize("bool_only", [False, True])
- def test_any_all_mixed_float(self, opname, axis, bool_only, float_string_frame):
+ def test_any_all_mixed_float(
+ self, all_boolean_reductions, axis, bool_only, float_string_frame
+ ):
# make sure op works on mixed-type frame
mixed = float_string_frame
mixed["_bool_"] = np.random.default_rng(2).standard_normal(len(mixed)) > 0.5
- getattr(mixed, opname)(axis=axis, bool_only=bool_only)
+ getattr(mixed, all_boolean_reductions)(axis=axis, bool_only=bool_only)
- @pytest.mark.parametrize("opname", ["any", "all"])
@pytest.mark.parametrize("axis", [0, 1])
- def test_any_all_bool_with_na(self, opname, axis, bool_frame_with_na):
- getattr(bool_frame_with_na, opname)(axis=axis, bool_only=False)
+ def test_any_all_bool_with_na(
+ self, all_boolean_reductions, axis, bool_frame_with_na
+ ):
+ getattr(bool_frame_with_na, all_boolean_reductions)(axis=axis, bool_only=False)
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")
- @pytest.mark.parametrize("opname", ["any", "all"])
- def test_any_all_bool_frame(self, opname, bool_frame_with_na):
+ def test_any_all_bool_frame(self, all_boolean_reductions, bool_frame_with_na):
# GH#12863: numpy gives back non-boolean data for object type
# so fill NaNs to compare with pandas behavior
frame = bool_frame_with_na.fillna(True)
- alternative = getattr(np, opname)
- f = getattr(frame, opname)
+ alternative = getattr(np, all_boolean_reductions)
+ f = getattr(frame, all_boolean_reductions)
def skipna_wrapper(x):
nona = x.dropna().values
@@ -1308,9 +1307,9 @@ def wrapper(x):
# all NA case
all_na = frame * np.nan
- r0 = getattr(all_na, opname)(axis=0)
- r1 = getattr(all_na, opname)(axis=1)
- if opname == "any":
+ r0 = getattr(all_na, all_boolean_reductions)(axis=0)
+ r1 = getattr(all_na, all_boolean_reductions)(axis=1)
+ if all_boolean_reductions == "any":
assert not r0.any()
assert not r1.any()
else:
@@ -1351,10 +1350,8 @@ def test_any_all_extra(self):
assert result is True
@pytest.mark.parametrize("axis", [0, 1])
- @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_any_all_object_dtype(
- self, axis, bool_agg_func, skipna, using_infer_string
+ self, axis, all_boolean_reductions, skipna, using_infer_string
):
# GH#35450
df = DataFrame(
@@ -1367,10 +1364,10 @@ def test_any_all_object_dtype(
)
if using_infer_string:
# na in object is True while in string pyarrow numpy it's false
- val = not axis == 0 and not skipna and bool_agg_func == "all"
+ val = not axis == 0 and not skipna and all_boolean_reductions == "all"
else:
val = True
- result = getattr(df, bool_agg_func)(axis=axis, skipna=skipna)
+ result = getattr(df, all_boolean_reductions)(axis=axis, skipna=skipna)
expected = Series([True, True, val, True])
tm.assert_series_equal(result, expected)
@@ -1737,27 +1734,26 @@ def test_reduction_timedelta_smallest_unit(self):
class TestNuisanceColumns:
- @pytest.mark.parametrize("method", ["any", "all"])
- def test_any_all_categorical_dtype_nuisance_column(self, method):
+ def test_any_all_categorical_dtype_nuisance_column(self, all_boolean_reductions):
# 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 support reduction"):
- getattr(ser, method)()
+ getattr(ser, all_boolean_reductions)()
with pytest.raises(TypeError, match="does not support reduction"):
- getattr(np, method)(ser)
+ getattr(np, all_boolean_reductions)(ser)
with pytest.raises(TypeError, match="does not support reduction"):
- getattr(df, method)(bool_only=False)
+ getattr(df, all_boolean_reductions)(bool_only=False)
with pytest.raises(TypeError, match="does not support reduction"):
- getattr(df, method)(bool_only=None)
+ getattr(df, all_boolean_reductions)(bool_only=None)
with pytest.raises(TypeError, match="does not support reduction"):
- getattr(np, method)(df, axis=0)
+ getattr(np, all_boolean_reductions)(df, axis=0)
def test_median_categorical_dtype_nuisance_column(self):
# GH#21020 DataFrame.median should match Series.median
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index ea66290ab0417..90524861ce311 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -2201,7 +2201,6 @@ def __init__(self, *args, **kwargs) -> None:
),
)
@pytest.mark.parametrize("stack_lev", range(2))
- @pytest.mark.parametrize("sort", [True, False])
def test_stack_order_with_unsorted_levels(
self, levels, stack_lev, sort, future_stack
):
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py
index ee694129f7118..89404a9bd09a3 100644
--- a/pandas/tests/groupby/aggregate/test_numba.py
+++ b/pandas/tests/groupby/aggregate/test_numba.py
@@ -53,7 +53,6 @@ def incorrect_function(values, index):
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-@pytest.mark.parametrize("as_index", [True, False])
def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython, as_index):
pytest.importorskip("numba")
diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py
index dce3f072ed903..331dbd85e0f36 100644
--- a/pandas/tests/groupby/conftest.py
+++ b/pandas/tests/groupby/conftest.py
@@ -13,26 +13,6 @@
)
-@pytest.fixture(params=[True, False])
-def sort(request):
- return request.param
-
-
-@pytest.fixture(params=[True, False])
-def as_index(request):
- return request.param
-
-
-@pytest.fixture(params=[True, False])
-def dropna(request):
- return request.param
-
-
-@pytest.fixture(params=[True, False])
-def observed(request):
- return request.param
-
-
@pytest.fixture
def df():
return DataFrame(
@@ -153,28 +133,6 @@ def groupby_func(request):
return request.param
-@pytest.fixture(params=[True, False])
-def parallel(request):
- """parallel keyword argument for numba.jit"""
- return request.param
-
-
-# Can parameterize nogil & nopython over True | False, but limiting per
-# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
-
-
-@pytest.fixture(params=[False])
-def nogil(request):
- """nogil keyword argument for numba.jit"""
- return request.param
-
-
-@pytest.fixture(params=[True])
-def nopython(request):
- """nopython keyword argument for numba.jit"""
- return request.param
-
-
@pytest.fixture(
params=[
("mean", {}),
diff --git a/pandas/tests/groupby/methods/test_describe.py b/pandas/tests/groupby/methods/test_describe.py
index a2440e09dfc02..f27e99809176c 100644
--- a/pandas/tests/groupby/methods/test_describe.py
+++ b/pandas/tests/groupby/methods/test_describe.py
@@ -149,7 +149,6 @@ def test_frame_describe_unstacked_format():
"indexing past lexsort depth may impact performance:"
"pandas.errors.PerformanceWarning"
)
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]])
def test_describe_with_duplicate_output_column_names(as_index, keys):
# GH 35314
diff --git a/pandas/tests/groupby/methods/test_nlargest_nsmallest.py b/pandas/tests/groupby/methods/test_nlargest_nsmallest.py
index bf983f04a3f3f..1225c325c4c23 100644
--- a/pandas/tests/groupby/methods/test_nlargest_nsmallest.py
+++ b/pandas/tests/groupby/methods/test_nlargest_nsmallest.py
@@ -99,17 +99,16 @@ def test_nsmallest():
[([0, 1, 2, 3], [0, 0, 1, 1]), ([0], [0])],
)
@pytest.mark.parametrize("dtype", [None, *tm.ALL_INT_NUMPY_DTYPES])
-@pytest.mark.parametrize("method", ["nlargest", "nsmallest"])
-def test_nlargest_and_smallest_noop(data, groups, dtype, method):
+def test_nlargest_and_smallest_noop(data, groups, dtype, nselect_method):
# GH 15272, GH 16345, GH 29129
# Test nlargest/smallest when it results in a noop,
# i.e. input is sorted and group size <= n
if dtype is not None:
data = np.array(data, dtype=dtype)
- if method == "nlargest":
+ if nselect_method == "nlargest":
data = list(reversed(data))
ser = Series(data, name="a")
- result = getattr(ser.groupby(groups), method)(n=2)
+ result = getattr(ser.groupby(groups), nselect_method)(n=2)
expidx = np.array(groups, dtype=int) if isinstance(groups, list) else groups
expected = Series(data, index=MultiIndex.from_arrays([expidx, ser.index]), name="a")
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/groupby/methods/test_nth.py b/pandas/tests/groupby/methods/test_nth.py
index a8ed9e9d52021..52d63cb720485 100644
--- a/pandas/tests/groupby/methods/test_nth.py
+++ b/pandas/tests/groupby/methods/test_nth.py
@@ -529,7 +529,6 @@ def test_nth_multi_index_as_expected():
],
)
@pytest.mark.parametrize("columns", [None, [], ["A"], ["B"], ["A", "B"]])
-@pytest.mark.parametrize("as_index", [True, False])
def test_groupby_head_tail(op, n, expected_rows, columns, as_index):
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
g = df.groupby("A", as_index=as_index)
diff --git a/pandas/tests/groupby/methods/test_rank.py b/pandas/tests/groupby/methods/test_rank.py
index a3b7da3fa836c..18869033d05c6 100644
--- a/pandas/tests/groupby/methods/test_rank.py
+++ b/pandas/tests/groupby/methods/test_rank.py
@@ -480,19 +480,17 @@ def test_rank_avg_even_vals(dtype, upper):
tm.assert_frame_equal(result, exp_df)
-@pytest.mark.parametrize("ties_method", ["average", "min", "max", "first", "dense"])
-@pytest.mark.parametrize("ascending", [True, False])
@pytest.mark.parametrize("na_option", ["keep", "top", "bottom"])
@pytest.mark.parametrize("pct", [True, False])
@pytest.mark.parametrize(
"vals", [["bar", "bar", "foo", "bar", "baz"], ["bar", np.nan, "foo", np.nan, "baz"]]
)
-def test_rank_object_dtype(ties_method, ascending, na_option, pct, vals):
+def test_rank_object_dtype(rank_method, ascending, na_option, pct, vals):
df = DataFrame({"key": ["foo"] * 5, "val": vals})
mask = df["val"].isna()
gb = df.groupby("key")
- res = gb.rank(method=ties_method, ascending=ascending, na_option=na_option, pct=pct)
+ res = gb.rank(method=rank_method, ascending=ascending, na_option=na_option, pct=pct)
# construct our expected by using numeric values with the same ordering
if mask.any():
@@ -502,15 +500,13 @@ def test_rank_object_dtype(ties_method, ascending, na_option, pct, vals):
gb2 = df2.groupby("key")
alt = gb2.rank(
- method=ties_method, ascending=ascending, na_option=na_option, pct=pct
+ method=rank_method, ascending=ascending, na_option=na_option, pct=pct
)
tm.assert_frame_equal(res, alt)
@pytest.mark.parametrize("na_option", [True, "bad", 1])
-@pytest.mark.parametrize("ties_method", ["average", "min", "max", "first", "dense"])
-@pytest.mark.parametrize("ascending", [True, False])
@pytest.mark.parametrize("pct", [True, False])
@pytest.mark.parametrize(
"vals",
@@ -520,13 +516,13 @@ def test_rank_object_dtype(ties_method, ascending, na_option, pct, vals):
[1, np.nan, 2, np.nan, 3],
],
)
-def test_rank_naoption_raises(ties_method, ascending, na_option, pct, vals):
+def test_rank_naoption_raises(rank_method, ascending, na_option, pct, vals):
df = DataFrame({"key": ["foo"] * 5, "val": vals})
msg = "na_option must be one of 'keep', 'top', or 'bottom'"
with pytest.raises(ValueError, match=msg):
df.groupby("key").rank(
- method=ties_method, ascending=ascending, na_option=na_option, pct=pct
+ method=rank_method, ascending=ascending, na_option=na_option, pct=pct
)
diff --git a/pandas/tests/groupby/methods/test_size.py b/pandas/tests/groupby/methods/test_size.py
index 93a4e743d0d71..fd55ceedd1083 100644
--- a/pandas/tests/groupby/methods/test_size.py
+++ b/pandas/tests/groupby/methods/test_size.py
@@ -32,6 +32,7 @@ def test_size(df, by):
pytest.param([None, None, None, None], marks=pytest.mark.xfail),
],
)
+@pytest.mark.parametrize("axis_1", [1, "columns"])
def test_size_axis_1(df, axis_1, by, sort, dropna):
# GH#45715
counts = {key: sum(value == key for value in by) for key in dict.fromkeys(by)}
@@ -51,7 +52,6 @@ def test_size_axis_1(df, axis_1, by, sort, dropna):
@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
-@pytest.mark.parametrize("sort", [True, False])
def test_size_sort(sort, by):
df = DataFrame(np.random.default_rng(2).choice(20, (1000, 3)), columns=list("ABC"))
left = df.groupby(by=by, sort=sort).size()
@@ -83,7 +83,6 @@ def test_size_period_index():
tm.assert_series_equal(result, ser)
-@pytest.mark.parametrize("as_index", [True, False])
def test_size_on_categorical(as_index):
df = DataFrame([[1, 1], [2, 2]], columns=["A", "B"])
df["A"] = df["A"].astype("category")
diff --git a/pandas/tests/groupby/methods/test_value_counts.py b/pandas/tests/groupby/methods/test_value_counts.py
index 2fa79c815d282..5c9f7febe32b3 100644
--- a/pandas/tests/groupby/methods/test_value_counts.py
+++ b/pandas/tests/groupby/methods/test_value_counts.py
@@ -76,9 +76,6 @@ def seed_df(seed_nans, n, m):
@pytest.mark.parametrize("bins", [None, [0, 5]], ids=repr)
@pytest.mark.parametrize("isort", [True, False])
@pytest.mark.parametrize("normalize, name", [(True, "proportion"), (False, "count")])
-@pytest.mark.parametrize("sort", [True, False])
-@pytest.mark.parametrize("ascending", [True, False])
-@pytest.mark.parametrize("dropna", [True, False])
def test_series_groupby_value_counts(
seed_nans,
num_rows,
@@ -295,7 +292,6 @@ def _frame_value_counts(df, keys, normalize, sort, ascending):
(True, False),
],
)
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize("frame", [True, False])
def test_against_frame_and_seriesgroupby(
education_df, groupby, normalize, name, sort, ascending, as_index, frame, request
@@ -583,7 +579,6 @@ def test_data_frame_value_counts_dropna(
tm.assert_series_equal(result_frame_groupby, expected)
-@pytest.mark.parametrize("as_index", [False, True])
@pytest.mark.parametrize("observed", [False, True])
@pytest.mark.parametrize(
"normalize, name, expected_data",
@@ -693,7 +688,6 @@ def assert_categorical_single_grouper(
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize(
"normalize, name, expected_data",
[
@@ -751,7 +745,6 @@ def test_categorical_single_grouper_observed_true(
)
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize(
"normalize, name, expected_data",
[
@@ -838,7 +831,6 @@ def test_categorical_single_grouper_observed_false(
)
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize(
"observed, expected_index",
[
@@ -924,7 +916,6 @@ def test_categorical_multiple_groupers(
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("as_index", [False, True])
@pytest.mark.parametrize("observed", [False, True])
@pytest.mark.parametrize(
"normalize, name, expected_data",
@@ -1033,7 +1024,6 @@ def test_mixed_groupings(normalize, expected_label, expected_values):
("level", list("abcd") + ["level_1"], ["a", None, "d", "b", "c", "level_1"]),
],
)
-@pytest.mark.parametrize("as_index", [False, True])
def test_column_label_duplicates(test, columns, expected_names, as_index):
# GH 44992
# Test for duplicate input column labels and generated duplicate labels
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index 34b6e7c4cde5f..f4b228eb5b326 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -1282,7 +1282,6 @@ def test_apply_by_cols_equals_apply_by_rows_transposed():
tm.assert_frame_equal(by_cols, df)
-@pytest.mark.parametrize("dropna", [True, False])
def test_apply_dropna_with_indexed_same(dropna):
# GH 38227
# GH#43205
@@ -1394,7 +1393,6 @@ def test_groupby_apply_to_series_name():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("dropna", [True, False])
def test_apply_na(dropna):
# GH#28984
df = DataFrame(
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 7a91601bf688f..a2cc7fd782396 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -618,7 +618,6 @@ def test_dataframe_categorical_with_nan(observed):
@pytest.mark.parametrize("ordered", [True, False])
@pytest.mark.parametrize("observed", [True, False])
-@pytest.mark.parametrize("sort", [True, False])
def test_dataframe_categorical_ordered_observed_sort(ordered, observed, sort):
# GH 25871: Fix groupby sorting on ordered Categoricals
# GH 25167: Groupby with observed=True doesn't sort
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 3cc06ae4d2387..038f59f8ea80f 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -295,7 +295,6 @@ def f(x, q=None, axis=0):
tm.assert_frame_equal(apply_result, expected, check_names=False)
-@pytest.mark.parametrize("as_index", [True, False])
def test_pass_args_kwargs_duplicate_columns(tsframe, as_index):
# go through _aggregate_frame with self.axis == 0 and duplicate columns
tsframe.columns = ["A", "B", "A", "C"]
diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py
index 73638eba0a3b3..ca097bc2be8bb 100644
--- a/pandas/tests/groupby/test_groupby_dropna.py
+++ b/pandas/tests/groupby/test_groupby_dropna.py
@@ -167,7 +167,6 @@ def test_groupby_dropna_series_by(dropna, expected):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("dropna", (False, True))
def test_grouper_dropna_propagation(dropna):
# GH 36604
df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]})
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py
index 363ff883385db..782bb7eb7984e 100644
--- a/pandas/tests/groupby/test_grouping.py
+++ b/pandas/tests/groupby/test_grouping.py
@@ -649,7 +649,6 @@ def test_groupby_multiindex_partial_indexing_equivalence(self):
result_groups = df.groupby([("a", 1)])["b"].groups
tm.assert_dict_equal(expected_groups, result_groups)
- @pytest.mark.parametrize("sort", [True, False])
def test_groupby_level(self, sort, multiindex_dataframe_random_data, df):
# GH 17537
frame = multiindex_dataframe_random_data
@@ -708,7 +707,6 @@ def test_groupby_level_index_names(self, axis):
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
df.groupby(level="foo", axis=axis)
- @pytest.mark.parametrize("sort", [True, False])
def test_groupby_level_with_nas(self, sort):
# GH 17537
index = MultiIndex(
diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py
index 3180a92be1236..6c029c10817d9 100644
--- a/pandas/tests/groupby/test_missing.py
+++ b/pandas/tests/groupby/test_missing.py
@@ -109,7 +109,6 @@ def test_fill_consistency():
@pytest.mark.parametrize("method", ["ffill", "bfill"])
-@pytest.mark.parametrize("dropna", [True, False])
@pytest.mark.parametrize("has_nan_group", [True, False])
def test_ffill_handles_nan_groups(dropna, method, has_nan_group):
# GH 34725
diff --git a/pandas/tests/groupby/test_reductions.py b/pandas/tests/groupby/test_reductions.py
index 8333dba439be9..273734e84d9aa 100644
--- a/pandas/tests/groupby/test_reductions.py
+++ b/pandas/tests/groupby/test_reductions.py
@@ -20,7 +20,6 @@
from pandas.util import _test_decorators as td
-@pytest.mark.parametrize("agg_func", ["any", "all"])
@pytest.mark.parametrize(
"vals",
[
@@ -39,20 +38,20 @@
[np.nan, np.nan, np.nan],
],
)
-def test_groupby_bool_aggs(skipna, agg_func, vals):
+def test_groupby_bool_aggs(skipna, all_boolean_reductions, vals):
df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2})
# Figure out expectation using Python builtin
- exp = getattr(builtins, agg_func)(vals)
+ exp = getattr(builtins, all_boolean_reductions)(vals)
# edge case for missing data with skipna and 'any'
- if skipna and all(isna(vals)) and agg_func == "any":
+ if skipna and all(isna(vals)) and all_boolean_reductions == "any":
exp = False
expected = DataFrame(
[exp] * 2, columns=["val"], index=pd.Index(["a", "b"], name="key")
)
- result = getattr(df.groupby("key"), agg_func)(skipna=skipna)
+ result = getattr(df.groupby("key"), all_boolean_reductions)(skipna=skipna)
tm.assert_frame_equal(result, expected)
@@ -69,18 +68,16 @@ def test_any():
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
-def test_bool_aggs_dup_column_labels(bool_agg_func):
+def test_bool_aggs_dup_column_labels(all_boolean_reductions):
# GH#21668
df = DataFrame([[True, True]], columns=["a", "a"])
grp_by = df.groupby([0])
- result = getattr(grp_by, bool_agg_func)()
+ result = getattr(grp_by, all_boolean_reductions)()
expected = df.set_axis(np.array([0]))
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
@pytest.mark.parametrize(
"data",
[
@@ -92,16 +89,16 @@ def test_bool_aggs_dup_column_labels(bool_agg_func):
[True, pd.NA, False],
],
)
-def test_masked_kleene_logic(bool_agg_func, skipna, data):
+def test_masked_kleene_logic(all_boolean_reductions, skipna, data):
# GH#37506
ser = Series(data, dtype="boolean")
# The result should match aggregating on the whole series. Correctness
# there is verified in test_reductions.py::test_any_all_boolean_kleene_logic
- expected_data = getattr(ser, bool_agg_func)(skipna=skipna)
+ expected_data = getattr(ser, all_boolean_reductions)(skipna=skipna)
expected = Series(expected_data, index=np.array([0]), dtype="boolean")
- result = ser.groupby([0, 0, 0]).agg(bool_agg_func, skipna=skipna)
+ result = ser.groupby([0, 0, 0]).agg(all_boolean_reductions, skipna=skipna)
tm.assert_series_equal(result, expected)
@@ -146,17 +143,18 @@ def test_masked_mixed_types(dtype1, dtype2, exp_col1, exp_col2):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])
-def test_masked_bool_aggs_skipna(bool_agg_func, dtype, skipna, frame_or_series):
+def test_masked_bool_aggs_skipna(
+ all_boolean_reductions, dtype, skipna, frame_or_series
+):
# GH#40585
obj = frame_or_series([pd.NA, 1], dtype=dtype)
expected_res = True
- if not skipna and bool_agg_func == "all":
+ if not skipna and all_boolean_reductions == "all":
expected_res = pd.NA
expected = frame_or_series([expected_res], index=np.array([1]), dtype="boolean")
- result = obj.groupby([1, 1]).agg(bool_agg_func, skipna=skipna)
+ result = obj.groupby([1, 1]).agg(all_boolean_reductions, skipna=skipna)
tm.assert_equal(result, expected)
@@ -177,20 +175,18 @@ def test_object_type_missing_vals(bool_agg_func, data, expected_res, frame_or_se
tm.assert_equal(result, expected)
-@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
-def test_object_NA_raises_with_skipna_false(bool_agg_func):
+def test_object_NA_raises_with_skipna_false(all_boolean_reductions):
# GH#37501
ser = Series([pd.NA], dtype=object)
with pytest.raises(TypeError, match="boolean value of NA is ambiguous"):
- ser.groupby([1]).agg(bool_agg_func, skipna=False)
+ ser.groupby([1]).agg(all_boolean_reductions, skipna=False)
-@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
-def test_empty(frame_or_series, bool_agg_func):
+def test_empty(frame_or_series, all_boolean_reductions):
# GH 45231
kwargs = {"columns": ["a"]} if frame_or_series is DataFrame else {"name": "a"}
obj = frame_or_series(**kwargs, dtype=object)
- result = getattr(obj.groupby(obj.index), bool_agg_func)()
+ result = getattr(obj.groupby(obj.index), all_boolean_reductions)()
expected = frame_or_series(**kwargs, dtype=bool)
tm.assert_equal(result, expected)
@@ -638,9 +634,6 @@ def test_max_nan_bug():
@pytest.mark.slow
-@pytest.mark.parametrize("sort", [False, True])
-@pytest.mark.parametrize("dropna", [False, True])
-@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize("with_nan", [True, False])
@pytest.mark.parametrize("keys", [["joe"], ["joe", "jim"]])
def test_series_groupby_nunique(sort, dropna, as_index, with_nan, keys):
@@ -1024,8 +1017,6 @@ def test_apply_to_nullable_integer_returns_float(values, function):
],
)
@pytest.mark.parametrize("axis", [0, 1])
-@pytest.mark.parametrize("skipna", [True, False])
-@pytest.mark.parametrize("sort", [True, False])
def test_regression_allowlist_methods(op, axis, skipna, sort):
# GH6944
# GH 17537
diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py
index 61fcc930f116a..af11dae0aabfe 100644
--- a/pandas/tests/groupby/transform/test_numba.py
+++ b/pandas/tests/groupby/transform/test_numba.py
@@ -51,7 +51,6 @@ def incorrect_function(values, index):
# Filter warnings when parallel=True and the function can't be parallelized by Numba
@pytest.mark.parametrize("jit", [True, False])
@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"])
-@pytest.mark.parametrize("as_index", [True, False])
def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython, as_index):
pytest.importorskip("numba")
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index a2ecd6c65db60..f7a4233b3ddc9 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1239,15 +1239,14 @@ def test_groupby_transform_dtype():
tm.assert_series_equal(result, expected1)
-@pytest.mark.parametrize("func", ["cumsum", "cumprod", "cummin", "cummax"])
-def test_transform_absent_categories(func):
+def test_transform_absent_categories(all_numeric_accumulations):
# GH 16771
# cython transforms with more groups than rows
x_vals = [1]
x_cats = range(2)
y = [1]
df = DataFrame({"x": Categorical(x_vals, x_cats), "y": y})
- result = getattr(df.y.groupby(df.x, observed=False), func)()
+ result = getattr(df.y.groupby(df.x, observed=False), all_numeric_accumulations)()
expected = df.y
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexes/conftest.py b/pandas/tests/indexes/conftest.py
index bfb7acdcf4812..61f6be000cee8 100644
--- a/pandas/tests/indexes/conftest.py
+++ b/pandas/tests/indexes/conftest.py
@@ -15,8 +15,7 @@ def sort(request):
Caution:
Don't confuse this one with the "sort" fixture used
- for DataFrame.append or concat. That one has
- parameters [True, False].
+ for concat. That one has parameters [True, False].
We can't combine them as sort=True is not permitted
in the Index setops methods.
diff --git a/pandas/tests/indexes/datetimes/methods/test_snap.py b/pandas/tests/indexes/datetimes/methods/test_snap.py
index 7064e9e7993f8..651e4383a3fac 100644
--- a/pandas/tests/indexes/datetimes/methods/test_snap.py
+++ b/pandas/tests/indexes/datetimes/methods/test_snap.py
@@ -9,7 +9,6 @@
@pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"])
@pytest.mark.parametrize("name", [None, "my_dti"])
-@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_dti_snap(name, tz, unit):
dti = DatetimeIndex(
[
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index 44dd64e162413..019d434680661 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -1093,12 +1093,11 @@ def test_daterange_bug_456(self):
result = rng1.union(rng2)
assert isinstance(result, DatetimeIndex)
- @pytest.mark.parametrize("inclusive", ["left", "right", "neither", "both"])
- def test_bdays_and_open_boundaries(self, inclusive):
+ def test_bdays_and_open_boundaries(self, inclusive_endpoints_fixture):
# GH 6673
start = "2018-07-21" # Saturday
end = "2018-07-29" # Sunday
- result = date_range(start, end, freq="B", inclusive=inclusive)
+ result = date_range(start, end, freq="B", inclusive=inclusive_endpoints_fixture)
bday_start = "2018-07-23" # Monday
bday_end = "2018-07-27" # Friday
diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py
index b52eed8c509c6..f8b01f7985535 100644
--- a/pandas/tests/indexes/datetimes/test_formats.py
+++ b/pandas/tests/indexes/datetimes/test_formats.py
@@ -14,11 +14,6 @@
import pandas._testing as tm
-@pytest.fixture(params=["s", "ms", "us", "ns"])
-def unit(request):
- return request.param
-
-
def test_get_values_for_csv():
index = pd.date_range(freq="1D", periods=3, start="2017-01-01")
diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py
index fd03047b2c127..787461b944bd0 100644
--- a/pandas/tests/indexes/interval/test_indexing.py
+++ b/pandas/tests/indexes/interval/test_indexing.py
@@ -141,7 +141,6 @@ def test_get_loc_length_one_scalar(self, scalar, closed):
with pytest.raises(KeyError, match=str(scalar)):
index.get_loc(scalar)
- @pytest.mark.parametrize("other_closed", ["left", "right", "both", "neither"])
@pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)])
def test_get_loc_length_one_interval(self, left, right, closed, other_closed):
# GH 20921
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 63f9b2176dddd..89b991318be0d 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -865,12 +865,11 @@ def test_nbytes(self):
expected = 64 # 4 * 8 * 2
assert result == expected
- @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
- def test_set_closed(self, name, closed, new_closed):
+ def test_set_closed(self, name, closed, other_closed):
# GH 21670
index = interval_range(0, 5, closed=closed, name=name)
- result = index.set_closed(new_closed)
- expected = interval_range(0, 5, closed=new_closed, name=name)
+ result = index.set_closed(other_closed)
+ expected = interval_range(0, 5, closed=other_closed, name=name)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])
diff --git a/pandas/tests/indexes/interval/test_pickle.py b/pandas/tests/indexes/interval/test_pickle.py
index 308a90e72eab5..c52106e5f0786 100644
--- a/pandas/tests/indexes/interval/test_pickle.py
+++ b/pandas/tests/indexes/interval/test_pickle.py
@@ -1,11 +1,8 @@
-import pytest
-
from pandas import IntervalIndex
import pandas._testing as tm
class TestPickle:
- @pytest.mark.parametrize("closed", ["left", "right", "both"])
def test_pickle_round_trip_closed(self, closed):
# https://github.com/pandas-dev/pandas/issues/35658
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index 4fd807e1827dd..dc5a6719284a6 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -237,9 +237,9 @@ def test_logical_compat(self, simple_index):
class TestNumericInt:
- @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8, np.uint64])
- def dtype(self, request):
- return request.param
+ @pytest.fixture
+ def dtype(self, any_int_numpy_dtype):
+ return np.dtype(any_int_numpy_dtype)
@pytest.fixture
def simple_index(self, dtype):
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 666d92064c86c..158cba9dfdded 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -721,12 +721,11 @@ def test_format_missing(self, vals, nulls_fixture):
assert formatted == expected
assert index[3] is nulls_fixture
- @pytest.mark.parametrize("op", ["any", "all"])
- def test_logical_compat(self, op, simple_index):
+ def test_logical_compat(self, all_boolean_reductions, simple_index):
index = simple_index
- left = getattr(index, op)()
- assert left == getattr(index.values, op)()
- right = getattr(index.to_series(), op)()
+ left = getattr(index, all_boolean_reductions)()
+ assert left == getattr(index.values, all_boolean_reductions)()
+ right = getattr(index.to_series(), all_boolean_reductions)()
# left might not match right exactly in e.g. string cases where the
# because we use np.any/all instead of .any/all
assert bool(left) == bool(right)
diff --git a/pandas/tests/indexes/test_datetimelike.py b/pandas/tests/indexes/test_datetimelike.py
index 21a686e8bc05b..330ea50dc1373 100644
--- a/pandas/tests/indexes/test_datetimelike.py
+++ b/pandas/tests/indexes/test_datetimelike.py
@@ -162,7 +162,6 @@ def test_where_cast_str(self, simple_index):
result = index.where(mask, ["foo"])
tm.assert_index_equal(result, expected)
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_diff(self, unit):
# GH 55080
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index 4a6982cf98670..8f4dd1c64236a 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -56,6 +56,11 @@ def any_dtype_for_small_pos_integer_indexes(request):
return request.param
+@pytest.fixture
+def index_flat2(index_flat):
+ return index_flat
+
+
def test_union_same_types(index):
# Union with a non-unique, non-monotonic index raises error
# Only needed for bool index factory
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 1aa988cca0400..ada6f88679673 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1681,10 +1681,10 @@ def test_loc_setitem_numpy_frame_categorical_value(self):
class TestLocWithEllipsis:
- @pytest.fixture(params=[tm.loc, tm.iloc])
- def indexer(self, request):
+ @pytest.fixture
+ def indexer(self, indexer_li):
# Test iloc while we're here
- return request.param
+ return indexer_li
@pytest.fixture
def obj(self, series_with_simple_index, frame_or_series):
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index 15c2b8d000b37..8bc6b48922a4f 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -304,7 +304,6 @@ def test_multi_chunk_pyarrow() -> None:
@pytest.mark.parametrize("tz", ["UTC", "US/Pacific"])
-@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_datetimetzdtype(tz, unit):
# GH 54239
tz_data = (
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index 6d5008ca9ee68..c49cbaf7fb26c 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -12,14 +12,14 @@
xlrd = pytest.importorskip("xlrd")
-@pytest.fixture(params=[".xls"])
-def read_ext_xlrd(request):
+@pytest.fixture
+def read_ext_xlrd():
"""
Valid extensions for reading Excel files with xlrd.
Similar to read_ext, but excludes .ods, .xlsb, and for xlrd>2 .xlsx, .xlsm
"""
- return request.param
+ return ".xls"
def test_read_xlrd_book(read_ext_xlrd, datapath):
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 0eefb0b52c483..9fa46222bce1a 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -957,7 +957,6 @@ def test_date_format_series_raises(self, datetime_series):
with pytest.raises(ValueError, match=msg):
ts.to_json(date_format="iso", date_unit="foo")
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_date_unit(self, unit, datetime_frame):
df = datetime_frame
df["date"] = Timestamp("20130101 20:43:42").as_unit("ns")
@@ -2026,9 +2025,6 @@ def test_json_uint64(self):
result = df.to_json(orient="split")
assert result == expected
- @pytest.mark.parametrize(
- "orient", ["split", "records", "values", "index", "columns"]
- )
def test_read_json_dtype_backend(
self, string_storage, dtype_backend, orient, using_infer_string
):
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index d8f362039ba13..700dcde336cd1 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -1326,9 +1326,8 @@ def test_read_with_parse_dates_invalid_type(all_parsers, parse_dates):
parser.read_csv(StringIO(data), parse_dates=(1,))
-@pytest.mark.parametrize("cache_dates", [True, False])
@pytest.mark.parametrize("value", ["nan", ""])
-def test_bad_date_parse(all_parsers, cache_dates, value):
+def test_bad_date_parse(all_parsers, cache, value):
# if we have an invalid date make sure that we handle this with
# and w/o the cache properly
parser = all_parsers
@@ -1339,13 +1338,12 @@ def test_bad_date_parse(all_parsers, cache_dates, value):
header=None,
names=["foo", "bar"],
parse_dates=["foo"],
- cache_dates=cache_dates,
+ cache_dates=cache,
)
-@pytest.mark.parametrize("cache_dates", [True, False])
@pytest.mark.parametrize("value", ["0"])
-def test_bad_date_parse_with_warning(all_parsers, cache_dates, value):
+def test_bad_date_parse_with_warning(all_parsers, cache, value):
# if we have an invalid date make sure that we handle this with
# and w/o the cache properly.
parser = all_parsers
@@ -1357,7 +1355,7 @@ def test_bad_date_parse_with_warning(all_parsers, cache_dates, value):
# TODO: parse dates directly in pyarrow, see
# https://github.com/pandas-dev/pandas/issues/48017
warn = None
- elif cache_dates:
+ elif cache:
# Note: warning is not raised if 'cache_dates', because here there is only a
# single unique date and hence no risk of inconsistent parsing.
warn = None
@@ -1370,7 +1368,7 @@ def test_bad_date_parse_with_warning(all_parsers, cache_dates, value):
header=None,
names=["foo", "bar"],
parse_dates=["foo"],
- cache_dates=cache_dates,
+ cache_dates=cache,
raise_on_extra_warnings=False,
)
diff --git a/pandas/tests/libs/test_join.py b/pandas/tests/libs/test_join.py
index ba2e6e7130929..bf8b4fabc54cb 100644
--- a/pandas/tests/libs/test_join.py
+++ b/pandas/tests/libs/test_join.py
@@ -138,14 +138,12 @@ def test_cython_inner_join(self):
tm.assert_numpy_array_equal(rs, exp_rs)
-@pytest.mark.parametrize("readonly", [True, False])
-def test_left_join_indexer_unique(readonly):
+def test_left_join_indexer_unique(writable):
a = np.array([1, 2, 3, 4, 5], dtype=np.int64)
b = np.array([2, 2, 3, 4, 4], dtype=np.int64)
- if readonly:
- # GH#37312, GH#37264
- a.setflags(write=False)
- b.setflags(write=False)
+ # GH#37312, GH#37264
+ a.setflags(write=writable)
+ b.setflags(write=writable)
result = libjoin.left_join_indexer_unique(b, a)
expected = np.array([1, 1, 2, 3, 3], dtype=np.intp)
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 30ec0d0affaa3..fcb5b65e59402 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -802,7 +802,6 @@ def test_var_masked_array(self, ddof, exp):
assert result == exp
@pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]"))
- @pytest.mark.parametrize("skipna", [True, False])
def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
# covers GH#11245
assert Series([], dtype=dtype).min(skipna=skipna) is NaT
@@ -986,32 +985,27 @@ def test_all_any_bool_only(self):
assert s.any(bool_only=True)
assert not s.all(bool_only=True)
- @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
- @pytest.mark.parametrize("skipna", [True, False])
- def test_any_all_object_dtype(self, bool_agg_func, skipna):
+ def test_any_all_object_dtype(self, all_boolean_reductions, skipna):
# GH#12863
ser = Series(["a", "b", "c", "d", "e"], dtype=object)
- result = getattr(ser, bool_agg_func)(skipna=skipna)
+ result = getattr(ser, all_boolean_reductions)(skipna=skipna)
expected = True
assert result == expected
- @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
@pytest.mark.parametrize(
"data", [[False, None], [None, False], [False, np.nan], [np.nan, False]]
)
- def test_any_all_object_dtype_missing(self, data, bool_agg_func):
+ def test_any_all_object_dtype_missing(self, data, all_boolean_reductions):
# GH#27709
ser = Series(data)
- result = getattr(ser, bool_agg_func)(skipna=False)
+ result = getattr(ser, all_boolean_reductions)(skipna=False)
# None is treated is False, but np.nan is treated as True
- expected = bool_agg_func == "any" and None not in data
+ expected = all_boolean_reductions == "any" and None not in data
assert result == expected
@pytest.mark.parametrize("dtype", ["boolean", "Int64", "UInt64", "Float64"])
- @pytest.mark.parametrize("bool_agg_func", ["any", "all"])
- @pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize(
# expected_data indexed as [[skipna=False/any, skipna=False/all],
# [skipna=True/any, skipna=True/all]]
@@ -1026,13 +1020,13 @@ def test_any_all_object_dtype_missing(self, data, bool_agg_func):
],
)
def test_any_all_nullable_kleene_logic(
- self, bool_agg_func, skipna, data, dtype, expected_data
+ self, all_boolean_reductions, skipna, data, dtype, expected_data
):
# GH-37506, GH-41967
ser = Series(data, dtype=dtype)
- expected = expected_data[skipna][bool_agg_func == "all"]
+ expected = expected_data[skipna][all_boolean_reductions == "all"]
- result = getattr(ser, bool_agg_func)(skipna=skipna)
+ result = getattr(ser, all_boolean_reductions)(skipna=skipna)
assert (result is pd.NA and expected is pd.NA) or result == expected
def test_any_axis1_bool_only(self):
@@ -1380,7 +1374,6 @@ def test_min_max_ordered(self, values, categories, function):
assert result == expected
@pytest.mark.parametrize("function", ["min", "max"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_min_max_ordered_with_nan_only(self, function, skipna):
# https://github.com/pandas-dev/pandas/issues/33450
cat = Series(Categorical([np.nan], categories=[1, 2], ordered=True))
@@ -1388,7 +1381,6 @@ def test_min_max_ordered_with_nan_only(self, function, skipna):
assert result is np.nan
@pytest.mark.parametrize("function", ["min", "max"])
- @pytest.mark.parametrize("skipna", [True, False])
def test_min_max_skipna(self, function, skipna):
cat = Series(
Categorical(["a", "b", np.nan, "a"], categories=["b", "a"], ordered=True)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 0dfe9877c4f86..f69649ab036d6 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -36,11 +36,6 @@
from pandas.tseries.offsets import Minute
-@pytest.fixture(params=["s", "ms", "us", "ns"])
-def unit(request):
- return request.param
-
-
@pytest.fixture
def simple_date_range_series():
"""
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index 7c70670d42908..309810b656ed3 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -176,7 +176,6 @@ def test_resample_with_timedelta_yields_no_empty_groups(duplicates):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_resample_quantile_timedelta(unit):
# GH: 29485
dtype = np.dtype(f"m8[{unit}]")
diff --git a/pandas/tests/reshape/concat/conftest.py b/pandas/tests/reshape/concat/conftest.py
deleted file mode 100644
index 62b8c59ba8855..0000000000000
--- a/pandas/tests/reshape/concat/conftest.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import pytest
-
-
-@pytest.fixture(params=[True, False])
-def sort(request):
- """Boolean sort keyword for concat and DataFrame.append."""
- return request.param
diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py
index f288921c25753..8aefa9262dbc5 100644
--- a/pandas/tests/reshape/concat/test_dataframe.py
+++ b/pandas/tests/reshape/concat/test_dataframe.py
@@ -194,7 +194,6 @@ def test_concat_duplicates_in_index_with_keys(self):
@pytest.mark.parametrize("ignore_index", [True, False])
@pytest.mark.parametrize("order", ["C", "F"])
- @pytest.mark.parametrize("axis", [0, 1])
def test_concat_copies(self, axis, order, ignore_index, using_copy_on_write):
# based on asv ConcatDataFrames
df = DataFrame(np.zeros((10, 5), dtype=np.float32, order=order))
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 2505d9163a6d2..e6488bcc4568f 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -455,13 +455,12 @@ def test_left_merge_empty_dataframe(self):
result = merge(right, left, on="key", how="right")
tm.assert_frame_equal(result, left)
- @pytest.mark.parametrize("how", ["inner", "left", "right", "outer"])
- def test_merge_empty_dataframe(self, index, how):
+ def test_merge_empty_dataframe(self, index, join_type):
# GH52777
left = DataFrame([], index=index[:0])
right = left.copy()
- result = left.join(right, how=how)
+ result = left.join(right, how=join_type)
tm.assert_frame_equal(result, left)
@pytest.mark.parametrize(
@@ -2814,9 +2813,8 @@ def test_merge_arrow_and_numpy_dtypes(dtype):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("how", ["inner", "left", "outer", "right"])
@pytest.mark.parametrize("tz", [None, "America/Chicago"])
-def test_merge_datetime_different_resolution(tz, how):
+def test_merge_datetime_different_resolution(tz, join_type):
# https://github.com/pandas-dev/pandas/issues/53200
vals = [
pd.Timestamp(2023, 5, 12, tz=tz),
@@ -2830,14 +2828,14 @@ def test_merge_datetime_different_resolution(tz, how):
expected = DataFrame({"t": vals, "a": [1.0, 2.0, np.nan], "b": [np.nan, 1.0, 2.0]})
expected["t"] = expected["t"].dt.as_unit("ns")
- if how == "inner":
+ if join_type == "inner":
expected = expected.iloc[[1]].reset_index(drop=True)
- elif how == "left":
+ elif join_type == "left":
expected = expected.iloc[[0, 1]]
- elif how == "right":
+ elif join_type == "right":
expected = expected.iloc[[1, 2]].reset_index(drop=True)
- result = df1.merge(df2, on="t", how=how)
+ result = df1.merge(df2, on="t", how=join_type)
tm.assert_frame_equal(result, expected)
@@ -2854,16 +2852,21 @@ def test_merge_multiindex_single_level():
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("how", ["left", "right", "inner", "outer"])
-@pytest.mark.parametrize("sort", [True, False])
@pytest.mark.parametrize("on_index", [True, False])
@pytest.mark.parametrize("left_unique", [True, False])
@pytest.mark.parametrize("left_monotonic", [True, False])
@pytest.mark.parametrize("right_unique", [True, False])
@pytest.mark.parametrize("right_monotonic", [True, False])
def test_merge_combinations(
- how, sort, on_index, left_unique, left_monotonic, right_unique, right_monotonic
+ join_type,
+ sort,
+ on_index,
+ left_unique,
+ left_monotonic,
+ right_unique,
+ right_monotonic,
):
+ how = join_type
# GH 54611
left = [2, 3]
if left_unique:
diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py
index b656191cc739d..33502f576dd2f 100644
--- a/pandas/tests/reshape/merge/test_merge_asof.py
+++ b/pandas/tests/reshape/merge/test_merge_asof.py
@@ -18,14 +18,6 @@
from pandas.core.reshape.merge import MergeError
-@pytest.fixture(params=["s", "ms", "us", "ns"])
-def unit(request):
- """
- Resolution for datetimelike dtypes.
- """
- return request.param
-
-
class TestAsOfMerge:
def prep_data(self, df, dedupe=False):
if dedupe:
diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py
index 269d3a2b7078e..bc02da0d5b97b 100644
--- a/pandas/tests/reshape/merge/test_multi.py
+++ b/pandas/tests/reshape/merge/test_multi.py
@@ -88,7 +88,6 @@ def test_merge_on_multikey(self, left, right, join_type):
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize("sort", [False, True])
def test_left_join_multi_index(self, sort):
icols = ["1st", "2nd", "3rd"]
@@ -150,7 +149,6 @@ def run_asserts(left, right, sort):
run_asserts(left, right, sort)
- @pytest.mark.parametrize("sort", [False, True])
def test_merge_right_vs_left(self, left, right, sort):
# compare left vs right merge with multikey
on_cols = ["key1", "key2"]
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index bf2717be4d7ae..6564ac0fd7e8a 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -30,11 +30,6 @@
from pandas.core.reshape.pivot import pivot_table
-@pytest.fixture(params=[True, False])
-def dropna(request):
- return request.param
-
-
@pytest.fixture(params=[([0] * 4, [1] * 4), (range(3), range(1, 4))])
def interval_values(request, closed):
left, right = request.param
@@ -2320,7 +2315,6 @@ def test_pivot_table_with_margins_and_numeric_columns(self):
tm.assert_frame_equal(result, expected)
- @pytest.mark.parametrize("dropna", [True, False])
def test_pivot_ea_dtype_dropna(self, dropna):
# GH#47477
df = DataFrame({"x": "a", "y": "b", "age": Series([20, 40], dtype="Int64")})
diff --git a/pandas/tests/scalar/timedelta/methods/test_round.py b/pandas/tests/scalar/timedelta/methods/test_round.py
index e54adb27d126b..676b44a4d54f4 100644
--- a/pandas/tests/scalar/timedelta/methods/test_round.py
+++ b/pandas/tests/scalar/timedelta/methods/test_round.py
@@ -170,7 +170,6 @@ def checker(ts, nanos, unit):
nanos = 24 * 60 * 60 * 1_000_000_000
checker(td, nanos, "D")
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_round_non_nano(self, unit):
td = Timedelta("1 days 02:34:57").as_unit(unit)
diff --git a/pandas/tests/scalar/timestamp/methods/test_normalize.py b/pandas/tests/scalar/timestamp/methods/test_normalize.py
index e097c9673e17a..60f249c602bd6 100644
--- a/pandas/tests/scalar/timestamp/methods/test_normalize.py
+++ b/pandas/tests/scalar/timestamp/methods/test_normalize.py
@@ -6,7 +6,6 @@
class TestTimestampNormalize:
@pytest.mark.parametrize("arg", ["2013-11-30", "2013-11-30 12:00:00"])
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_normalize(self, tz_naive_fixture, arg, unit):
tz = tz_naive_fixture
ts = Timestamp(arg, tz=tz).as_unit(unit)
diff --git a/pandas/tests/scalar/timestamp/methods/test_replace.py b/pandas/tests/scalar/timestamp/methods/test_replace.py
index 8a208455edc82..d67de79a8dd10 100644
--- a/pandas/tests/scalar/timestamp/methods/test_replace.py
+++ b/pandas/tests/scalar/timestamp/methods/test_replace.py
@@ -157,7 +157,6 @@ def test_replace_across_dst(self, tz, normalize):
ts2b = normalize(ts2)
assert ts2 == ts2b
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_replace_dst_border(self, unit):
# Gh 7825
t = Timestamp("2013-11-3", tz="America/Chicago").as_unit(unit)
@@ -168,7 +167,6 @@ def test_replace_dst_border(self, unit):
@pytest.mark.parametrize("fold", [0, 1])
@pytest.mark.parametrize("tz", ["dateutil/Europe/London", "Europe/London"])
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_replace_dst_fold(self, fold, tz, unit):
# GH 25017
d = datetime(2019, 10, 27, 2, 30)
diff --git a/pandas/tests/scalar/timestamp/methods/test_round.py b/pandas/tests/scalar/timestamp/methods/test_round.py
index d10ee18b47f19..59c0fe8bbebfb 100644
--- a/pandas/tests/scalar/timestamp/methods/test_round.py
+++ b/pandas/tests/scalar/timestamp/methods/test_round.py
@@ -147,7 +147,6 @@ def test_round_minute_freq(self, test_input, freq, expected, rounder):
result = func(freq)
assert result == expected
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_ceil(self, unit):
dt = Timestamp("20130101 09:10:11").as_unit(unit)
result = dt.ceil("D")
@@ -155,7 +154,6 @@ def test_ceil(self, unit):
assert result == expected
assert result._creso == dt._creso
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_floor(self, unit):
dt = Timestamp("20130101 09:10:11").as_unit(unit)
result = dt.floor("D")
diff --git a/pandas/tests/scalar/timestamp/methods/test_tz_localize.py b/pandas/tests/scalar/timestamp/methods/test_tz_localize.py
index af3dee1880d2e..0786cc58a4f95 100644
--- a/pandas/tests/scalar/timestamp/methods/test_tz_localize.py
+++ b/pandas/tests/scalar/timestamp/methods/test_tz_localize.py
@@ -50,7 +50,6 @@ def test_tz_localize_pushes_out_of_bounds(self):
with pytest.raises(OutOfBoundsDatetime, match=msg):
Timestamp.max.tz_localize("US/Pacific")
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_tz_localize_ambiguous_bool(self, unit):
# make sure that we are correctly accepting bool values as ambiguous
# GH#14402
@@ -295,7 +294,6 @@ def test_timestamp_tz_localize(self, tz):
],
)
@pytest.mark.parametrize("tz_type", ["", "dateutil/"])
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_timestamp_tz_localize_nonexistent_shift(
self, start_ts, tz, end_ts, shift, tz_type, unit
):
@@ -327,7 +325,6 @@ def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, warsaw):
with pytest.raises(ValueError, match=msg):
ts.tz_localize(tz, nonexistent=timedelta(seconds=offset))
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit):
# GH 8917
tz = warsaw
@@ -335,7 +332,6 @@ def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit):
result = ts.tz_localize(tz, nonexistent="NaT")
assert result is NaT
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
def test_timestamp_tz_localize_nonexistent_raise(self, warsaw, unit):
# GH 8917
tz = warsaw
diff --git a/pandas/tests/series/methods/test_map.py b/pandas/tests/series/methods/test_map.py
index 251d4063008b9..f4f72854e50d3 100644
--- a/pandas/tests/series/methods/test_map.py
+++ b/pandas/tests/series/methods/test_map.py
@@ -326,7 +326,6 @@ def test_map_dict_na_key():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_defaultdict_na_key(na_action):
# GH 48813
s = Series([1, 2, np.nan])
@@ -336,7 +335,6 @@ def test_map_defaultdict_na_key(na_action):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_defaultdict_missing_key(na_action):
# GH 48813
s = Series([1, 2, np.nan])
@@ -346,7 +344,6 @@ def test_map_defaultdict_missing_key(na_action):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_defaultdict_unmutated(na_action):
# GH 48813
s = Series([1, 2, np.nan])
@@ -483,7 +480,6 @@ def test_map_box_period():
tm.assert_series_equal(res, exp)
-@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map_categorical(na_action, using_infer_string):
values = pd.Categorical(list("ABBABCD"), categories=list("DCBA"), ordered=True)
s = Series(values, name="XX", index=list("abcdefg"))
diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py
index 24cf97c05c0a8..4d48f290e6a44 100644
--- a/pandas/tests/series/methods/test_rank.py
+++ b/pandas/tests/series/methods/test_rank.py
@@ -248,8 +248,6 @@ def test_rank_tie_methods(self, ser, results, dtype):
result = ser.rank(method=method)
tm.assert_series_equal(result, Series(exp))
- @pytest.mark.parametrize("ascending", [True, False])
- @pytest.mark.parametrize("method", ["average", "min", "max", "first", "dense"])
@pytest.mark.parametrize("na_option", ["top", "bottom", "keep"])
@pytest.mark.parametrize(
"dtype, na_value, pos_inf, neg_inf",
@@ -267,11 +265,11 @@ def test_rank_tie_methods(self, ser, results, dtype):
],
)
def test_rank_tie_methods_on_infs_nans(
- self, method, na_option, ascending, dtype, na_value, pos_inf, neg_inf
+ self, rank_method, na_option, ascending, dtype, na_value, pos_inf, neg_inf
):
pytest.importorskip("scipy")
if dtype == "float64[pyarrow]":
- if method == "average":
+ if rank_method == "average":
exp_dtype = "float64[pyarrow]"
else:
exp_dtype = "uint64[pyarrow]"
@@ -288,7 +286,7 @@ def test_rank_tie_methods_on_infs_nans(
"first": ([1, 2, 3], [4, 5, 6], [7, 8, 9]),
"dense": ([1, 1, 1], [2, 2, 2], [3, 3, 3]),
}
- ranks = exp_ranks[method]
+ ranks = exp_ranks[rank_method]
if na_option == "top":
order = [ranks[1], ranks[0], ranks[2]]
elif na_option == "bottom":
@@ -297,7 +295,9 @@ def test_rank_tie_methods_on_infs_nans(
order = [ranks[0], [np.nan] * chunk, ranks[1]]
expected = order if ascending else order[::-1]
expected = list(chain.from_iterable(expected))
- result = iseries.rank(method=method, na_option=na_option, ascending=ascending)
+ result = iseries.rank(
+ method=rank_method, na_option=na_option, ascending=ascending
+ )
tm.assert_series_equal(result, Series(expected, dtype=exp_dtype))
def test_rank_desc_mix_nans_infs(self):
@@ -308,7 +308,6 @@ def test_rank_desc_mix_nans_infs(self):
exp = Series([3, np.nan, 1, 4, 2], dtype="float64")
tm.assert_series_equal(result, exp)
- @pytest.mark.parametrize("method", ["average", "min", "max", "first", "dense"])
@pytest.mark.parametrize(
"op, value",
[
@@ -317,7 +316,7 @@ def test_rank_desc_mix_nans_infs(self):
[operator.mul, 1e-6],
],
)
- def test_rank_methods_series(self, method, op, value):
+ def test_rank_methods_series(self, rank_method, op, value):
sp_stats = pytest.importorskip("scipy.stats")
xs = np.random.default_rng(2).standard_normal(9)
@@ -327,8 +326,10 @@ def test_rank_methods_series(self, method, op, value):
index = [chr(ord("a") + i) for i in range(len(xs))]
vals = op(xs, value)
ts = Series(vals, index=index)
- result = ts.rank(method=method)
- sprank = sp_stats.rankdata(vals, method if method != "first" else "ordinal")
+ result = ts.rank(method=rank_method)
+ sprank = sp_stats.rankdata(
+ vals, rank_method if rank_method != "first" else "ordinal"
+ )
expected = Series(sprank, index=index).astype("float64")
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py
index 4808272879071..00142c4d82327 100644
--- a/pandas/tests/series/methods/test_sort_values.py
+++ b/pandas/tests/series/methods/test_sort_values.py
@@ -204,7 +204,6 @@ def test_sort_values_validate_ascending_for_value_error(self):
with pytest.raises(ValueError, match=msg):
ser.sort_values(ascending="False")
- @pytest.mark.parametrize("ascending", [False, 0, 1, True])
def test_sort_values_validate_ascending_functional(self, ascending):
# GH41634
ser = Series([23, 7, 21])
diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py
index e200f7d9933aa..0bc3092d30b43 100644
--- a/pandas/tests/series/test_reductions.py
+++ b/pandas/tests/series/test_reductions.py
@@ -70,7 +70,6 @@ def test_reductions_td64_with_nat():
assert ser.max() == exp
-@pytest.mark.parametrize("skipna", [True, False])
def test_td64_sum_empty(skipna):
# GH#37151
ser = Series([], dtype="timedelta64[ns]")
diff --git a/pandas/tests/strings/test_cat.py b/pandas/tests/strings/test_cat.py
index c1e7ad6e02779..68ca807bde145 100644
--- a/pandas/tests/strings/test_cat.py
+++ b/pandas/tests/strings/test_cat.py
@@ -16,6 +16,11 @@
)
+@pytest.fixture
+def index_or_series2(index_or_series):
+ return index_or_series
+
+
@pytest.mark.parametrize("other", [None, Series, Index])
def test_str_cat_name(index_or_series, other):
# GH 21053
@@ -270,14 +275,13 @@ def test_str_cat_mixed_inputs(index_or_series):
s.str.cat(iter([t.values, list(s)]))
-@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
-def test_str_cat_align_indexed(index_or_series, join):
+def test_str_cat_align_indexed(index_or_series, join_type):
# https://github.com/pandas-dev/pandas/issues/18657
box = index_or_series
s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
- sa, ta = s.align(t, join=join)
+ sa, ta = s.align(t, join=join_type)
# result after manual alignment of inputs
expected = sa.str.cat(ta, na_rep="-")
@@ -286,25 +290,24 @@ def test_str_cat_align_indexed(index_or_series, join):
sa = Index(sa)
expected = Index(expected)
- result = s.str.cat(t, join=join, na_rep="-")
+ result = s.str.cat(t, join=join_type, na_rep="-")
tm.assert_equal(result, expected)
-@pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
-def test_str_cat_align_mixed_inputs(join):
+def test_str_cat_align_mixed_inputs(join_type):
s = Series(["a", "b", "c", "d"])
t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
d = concat([t, t], axis=1)
expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
- expected = expected_outer.loc[s.index.join(t.index, how=join)]
+ expected = expected_outer.loc[s.index.join(t.index, how=join_type)]
# list of Series
- result = s.str.cat([t, t], join=join, na_rep="-")
+ result = s.str.cat([t, t], join=join_type, na_rep="-")
tm.assert_series_equal(result, expected)
# DataFrame
- result = s.str.cat(d, join=join, na_rep="-")
+ result = s.str.cat(d, join=join_type, na_rep="-")
tm.assert_series_equal(result, expected)
# mixed list of indexed/unindexed
@@ -313,19 +316,19 @@ def test_str_cat_align_mixed_inputs(join):
# joint index of rhs [t, u]; u will be forced have index of s
rhs_idx = (
t.index.intersection(s.index)
- if join == "inner"
+ if join_type == "inner"
else t.index.union(s.index)
- if join == "outer"
+ if join_type == "outer"
else t.index.append(s.index.difference(t.index))
)
- expected = expected_outer.loc[s.index.join(rhs_idx, how=join)]
- result = s.str.cat([t, u], join=join, na_rep="-")
+ expected = expected_outer.loc[s.index.join(rhs_idx, how=join_type)]
+ result = s.str.cat([t, u], join=join_type, na_rep="-")
tm.assert_series_equal(result, expected)
with pytest.raises(TypeError, match="others must be Series,.*"):
# nested lists are forbidden
- s.str.cat([t, list(u)], join=join)
+ s.str.cat([t, list(u)], join=join_type)
# errors for incorrect lengths
rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
@@ -333,11 +336,11 @@ def test_str_cat_align_mixed_inputs(join):
# unindexed object of wrong length
with pytest.raises(ValueError, match=rgx):
- s.str.cat(z, join=join)
+ s.str.cat(z, join=join_type)
# unindexed object of wrong length in list
with pytest.raises(ValueError, match=rgx):
- s.str.cat([t, z], join=join)
+ s.str.cat([t, z], join=join_type)
def test_str_cat_all_na(index_or_series, index_or_series2):
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 718d1b3ee2e83..16d684b72e1e3 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -63,7 +63,6 @@ def test_factorize_complex(self):
expected_uniques = np.array([(1 + 0j), (2 + 0j), (2 + 1j)], dtype=object)
tm.assert_numpy_array_equal(uniques, expected_uniques)
- @pytest.mark.parametrize("sort", [True, False])
def test_factorize(self, index_or_series_obj, sort):
obj = index_or_series_obj
result_codes, result_uniques = obj.factorize(sort=sort)
@@ -354,7 +353,6 @@ def test_datetime64_factorize(self, writable):
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_numpy_array_equal(uniques, expected_uniques)
- @pytest.mark.parametrize("sort", [True, False])
def test_factorize_rangeindex(self, sort):
# increasing -> sort doesn't matter
ri = pd.RangeIndex.from_range(range(10))
@@ -368,7 +366,6 @@ def test_factorize_rangeindex(self, sort):
tm.assert_numpy_array_equal(result[0], expected[0])
tm.assert_index_equal(result[1], expected[1], exact=True)
- @pytest.mark.parametrize("sort", [True, False])
def test_factorize_rangeindex_decreasing(self, sort):
# decreasing -> sort matters
ri = pd.RangeIndex.from_range(range(10))
@@ -431,7 +428,6 @@ def test_parametrized_factorize_na_value(self, data, na_value):
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_numpy_array_equal(uniques, expected_uniques)
- @pytest.mark.parametrize("sort", [True, False])
@pytest.mark.parametrize(
"data, uniques",
[
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index a50054f33f382..95d0953301a42 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -1102,10 +1102,6 @@ def prng(self):
class TestDatetime64NaNOps:
- @pytest.fixture(params=["s", "ms", "us", "ns"])
- def unit(self, request):
- return request.param
-
# Enabling mean changes the behavior of DataFrame.mean
# See https://github.com/pandas-dev/pandas/issues/24752
def test_nanmean(self, unit):
diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py
index 285f240028152..329fbac925539 100644
--- a/pandas/tests/test_sorting.py
+++ b/pandas/tests/test_sorting.py
@@ -218,14 +218,13 @@ def test_int64_overflow_check_sum_col(self, left_right):
assert result.name is None
@pytest.mark.slow
- @pytest.mark.parametrize("how", ["left", "right", "outer", "inner"])
- def test_int64_overflow_how_merge(self, left_right, how):
+ def test_int64_overflow_how_merge(self, left_right, join_type):
left, right = left_right
out = merge(left, right, how="outer")
out.sort_values(out.columns.tolist(), inplace=True)
out.index = np.arange(len(out))
- tm.assert_frame_equal(out, merge(left, right, how=how, sort=True))
+ tm.assert_frame_equal(out, merge(left, right, how=join_type, sort=True))
@pytest.mark.slow
def test_int64_overflow_sort_false_order(self, left_right):
@@ -239,10 +238,9 @@ def test_int64_overflow_sort_false_order(self, left_right):
tm.assert_frame_equal(right, out[right.columns.tolist()])
@pytest.mark.slow
- @pytest.mark.parametrize("how", ["left", "right", "outer", "inner"])
- @pytest.mark.parametrize("sort", [True, False])
- def test_int64_overflow_one_to_many_none_match(self, how, sort):
+ def test_int64_overflow_one_to_many_none_match(self, join_type, sort):
# one-2-many/none match
+ how = join_type
low, high, n = -1 << 10, 1 << 10, 1 << 11
left = DataFrame(
np.random.default_rng(2).integers(low, high, (n, 7)).astype("int64"),
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 6791ac0340640..5b856bc632a1d 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -62,21 +62,11 @@
)
-@pytest.fixture(params=[True, False])
-def cache(request):
- """
- cache keyword to pass to to_datetime.
- """
- return request.param
-
-
class TestTimeConversionFormats:
- @pytest.mark.parametrize("readonly", [True, False])
- def test_to_datetime_readonly(self, readonly):
+ def test_to_datetime_readonly(self, writable):
# GH#34857
arr = np.array([], dtype=object)
- if readonly:
- arr.setflags(write=False)
+ arr.setflags(write=writable)
result = to_datetime(arr)
expected = to_datetime([])
tm.assert_index_equal(result, expected)
@@ -1588,7 +1578,6 @@ def test_convert_object_to_datetime_with_cache(
)
tm.assert_series_equal(result_series, expected_series)
- @pytest.mark.parametrize("cache", [True, False])
@pytest.mark.parametrize(
"input",
[
@@ -3600,7 +3589,6 @@ def test_empty_string_datetime_coerce__unit():
tm.assert_index_equal(expected, result)
-@pytest.mark.parametrize("cache", [True, False])
def test_to_datetime_monotonic_increasing_index(cache):
# GH28238
cstart = start_caching_at
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py
index b67694f1c58c7..036462674c270 100644
--- a/pandas/tests/tools/test_to_timedelta.py
+++ b/pandas/tests/tools/test_to_timedelta.py
@@ -32,12 +32,10 @@ def test_to_timedelta_dt64_raises(self):
with pytest.raises(TypeError, match=msg):
ser.to_frame().apply(to_timedelta)
- @pytest.mark.parametrize("readonly", [True, False])
- def test_to_timedelta_readonly(self, readonly):
+ def test_to_timedelta_readonly(self, writable):
# GH#34857
arr = np.array([], dtype=object)
- if readonly:
- arr.setflags(write=False)
+ arr.setflags(write=writable)
result = to_timedelta(arr)
expected = to_timedelta([])
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py
index 99a504f4188c1..0d37273e89092 100644
--- a/pandas/tests/tseries/frequencies/test_inference.py
+++ b/pandas/tests/tseries/frequencies/test_inference.py
@@ -231,7 +231,6 @@ def test_infer_freq_index(freq, expected):
}.items()
),
)
-@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_infer_freq_tz(tz_naive_fixture, expected, dates, unit):
# see gh-7310, GH#55609
tz = tz_naive_fixture
diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py
index 2779100f5355c..e675977c6fab4 100644
--- a/pandas/tests/tseries/offsets/test_business_hour.py
+++ b/pandas/tests/tseries/offsets/test_business_hour.py
@@ -947,7 +947,6 @@ def test_apply_nanoseconds(self):
assert_offset_equal(offset, base, expected)
@pytest.mark.parametrize("td_unit", ["s", "ms", "us", "ns"])
- @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
def test_bday_ignores_timedeltas(self, unit, td_unit):
# GH#55608
idx = date_range("2010/02/01", "2010/02/10", freq="12h", unit=unit)
diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index 73ab470ab97a7..fe873b3b74254 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -50,28 +50,6 @@ def min_periods(request):
return request.param
-@pytest.fixture(params=[True, False])
-def parallel(request):
- """parallel keyword argument for numba.jit"""
- return request.param
-
-
-# Can parameterize nogil & nopython over True | False, but limiting per
-# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
-
-
-@pytest.fixture(params=[False])
-def nogil(request):
- """nogil keyword argument for numba.jit"""
- return request.param
-
-
-@pytest.fixture(params=[True])
-def nopython(request):
- """nopython keyword argument for numba.jit"""
- return request.param
-
-
@pytest.fixture(params=[True, False])
def adjust(request):
"""adjust keyword argument for ewm"""
diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py
index aebb9e86c763f..10d0afb5a2412 100644
--- a/pandas/tests/window/test_expanding.py
+++ b/pandas/tests/window/test_expanding.py
@@ -79,10 +79,10 @@ def test_missing_minp_zero():
tm.assert_series_equal(result, expected)
-def test_expanding_axis(axis_frame):
+def test_expanding_axis(axis):
# see gh-23372.
df = DataFrame(np.ones((10, 20)))
- axis = df._get_axis_number(axis_frame)
+ axis = df._get_axis_number(axis)
if axis == 0:
msg = "The 'axis' keyword in DataFrame.expanding is deprecated"
@@ -95,7 +95,7 @@ def test_expanding_axis(axis_frame):
expected = DataFrame([[np.nan] * 2 + [float(i) for i in range(3, 21)]] * 10)
with tm.assert_produces_warning(FutureWarning, match=msg):
- result = df.expanding(3, axis=axis_frame).sum()
+ result = df.expanding(3, axis=axis).sum()
tm.assert_frame_equal(result, expected)
@@ -241,7 +241,6 @@ def test_expanding_skew_kurt_numerical_stability(method):
@pytest.mark.parametrize("window", [1, 3, 10, 20])
@pytest.mark.parametrize("method", ["min", "max", "average"])
@pytest.mark.parametrize("pct", [True, False])
-@pytest.mark.parametrize("ascending", [True, False])
@pytest.mark.parametrize("test_data", ["default", "duplicates", "nans"])
def test_rank(window, method, pct, ascending, test_data):
length = 20
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index f353a7fa2f0fe..7ab6e7863ad81 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -594,10 +594,10 @@ def test_multi_index_names():
assert result.index.names == [None, "1", "2"]
-def test_rolling_axis_sum(axis_frame):
+def test_rolling_axis_sum(axis):
# see gh-23372.
df = DataFrame(np.ones((10, 20)))
- axis = df._get_axis_number(axis_frame)
+ axis = df._get_axis_number(axis)
if axis == 0:
msg = "The 'axis' keyword in DataFrame.rolling"
@@ -608,15 +608,15 @@ def test_rolling_axis_sum(axis_frame):
expected = DataFrame([[np.nan] * 2 + [3.0] * 18] * 10)
with tm.assert_produces_warning(FutureWarning, match=msg):
- result = df.rolling(3, axis=axis_frame).sum()
+ result = df.rolling(3, axis=axis).sum()
tm.assert_frame_equal(result, expected)
-def test_rolling_axis_count(axis_frame):
+def test_rolling_axis_count(axis):
# see gh-26055
df = DataFrame({"x": range(3), "y": range(3)})
- axis = df._get_axis_number(axis_frame)
+ axis = df._get_axis_number(axis)
if axis in [0, "index"]:
msg = "The 'axis' keyword in DataFrame.rolling"
@@ -626,7 +626,7 @@ def test_rolling_axis_count(axis_frame):
expected = DataFrame({"x": [1.0, 1.0, 1.0], "y": [2.0, 2.0, 2.0]})
with tm.assert_produces_warning(FutureWarning, match=msg):
- result = df.rolling(2, axis=axis_frame, min_periods=0).count()
+ result = df.rolling(2, axis=axis, min_periods=0).count()
tm.assert_frame_equal(result, expected)
@@ -639,21 +639,21 @@ def test_readonly_array():
tm.assert_series_equal(result, expected)
-def test_rolling_datetime(axis_frame, tz_naive_fixture):
+def test_rolling_datetime(axis, tz_naive_fixture):
# GH-28192
tz = tz_naive_fixture
df = DataFrame(
{i: [1] * 2 for i in date_range("2019-8-01", "2019-08-03", freq="D", tz=tz)}
)
- if axis_frame in [0, "index"]:
+ if axis in [0, "index"]:
msg = "The 'axis' keyword in DataFrame.rolling"
with tm.assert_produces_warning(FutureWarning, match=msg):
- result = df.T.rolling("2D", axis=axis_frame).sum().T
+ result = df.T.rolling("2D", axis=axis).sum().T
else:
msg = "Support for axis=1 in DataFrame.rolling"
with tm.assert_produces_warning(FutureWarning, match=msg):
- result = df.rolling("2D", axis=axis_frame).sum()
+ result = df.rolling("2D", axis=axis).sum()
expected = DataFrame(
{
**{
@@ -669,7 +669,6 @@ def test_rolling_datetime(axis_frame, tz_naive_fixture):
tm.assert_frame_equal(result, expected)
-@pytest.mark.parametrize("center", [True, False])
def test_rolling_window_as_string(center):
# see gh-22590
date_today = datetime.now()
@@ -1629,7 +1628,6 @@ def test_rolling_numeric_dtypes():
@pytest.mark.parametrize("window", [1, 3, 10, 20])
@pytest.mark.parametrize("method", ["min", "max", "average"])
@pytest.mark.parametrize("pct", [True, False])
-@pytest.mark.parametrize("ascending", [True, False])
@pytest.mark.parametrize("test_data", ["default", "duplicates", "nans"])
def test_rank(window, method, pct, ascending, test_data):
length = 20
@@ -1947,7 +1945,6 @@ def test_numeric_only_corr_cov_series(kernel, use_arg, numeric_only, dtype):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
@pytest.mark.parametrize("tz", [None, "UTC", "Europe/Prague"])
def test_rolling_timedelta_window_non_nanoseconds(unit, tz):
# Test Sum, GH#55106
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/56583 | 2023-12-20T23:34:59Z | 2024-01-02T19:17:08Z | 2024-01-02T19:17:08Z | 2024-01-03T21:56:29Z |
BUG: stack changes NA values in the index | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 8c475791df64d..5382e56544907 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -686,6 +686,7 @@ Reshaping
- Bug in :meth:`DataFrame.melt` where it would not preserve the datetime (:issue:`55254`)
- Bug in :meth:`DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`)
- Bug in :meth:`DataFrame.pivot` with numeric columns and extension dtype for data (:issue:`56528`)
+- Bug in :meth:`DataFrame.stack` and :meth:`Series.stack` with ``future_stack=True`` would not preserve NA values in the index (:issue:`56573`)
Sparse
^^^^^^
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 8c822ec58e011..7a49682d7c57c 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -953,8 +953,8 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame:
index_levels = frame.index.levels
index_codes = list(np.tile(frame.index.codes, (1, ratio)))
else:
- index_levels = [frame.index.unique()]
- codes = factorize(frame.index)[0]
+ codes, uniques = factorize(frame.index, use_na_sentinel=False)
+ index_levels = [uniques]
index_codes = list(np.tile(codes, (1, ratio)))
if isinstance(stack_cols, MultiIndex):
column_levels = ordered_stack_cols.levels
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 554a9d4ce2d5d..6e1e743eb60de 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -2638,3 +2638,41 @@ def test_stack_tuple_columns(future_stack):
),
)
tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "dtype, na_value",
+ [
+ ("float64", np.nan),
+ ("Float64", np.nan),
+ ("Float64", pd.NA),
+ ("Int64", pd.NA),
+ ],
+)
+@pytest.mark.parametrize("test_multiindex", [True, False])
+def test_stack_preserves_na(dtype, na_value, test_multiindex):
+ # GH#56573
+ if test_multiindex:
+ index = MultiIndex.from_arrays(2 * [Index([na_value], dtype=dtype)])
+ else:
+ index = Index([na_value], dtype=dtype)
+ df = DataFrame({"a": [1]}, index=index)
+ result = df.stack(future_stack=True)
+
+ if test_multiindex:
+ expected_index = MultiIndex.from_arrays(
+ [
+ Index([na_value], dtype=dtype),
+ Index([na_value], dtype=dtype),
+ Index(["a"]),
+ ]
+ )
+ else:
+ expected_index = MultiIndex.from_arrays(
+ [
+ Index([na_value], dtype=dtype),
+ Index(["a"]),
+ ]
+ )
+ expected = Series(1, index=expected_index)
+ tm.assert_series_equal(result, expected)
| - [x] closes #56573 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
~Still needs a bit more testing (MultiIndex inputs).~ | https://api.github.com/repos/pandas-dev/pandas/pulls/56582 | 2023-12-20T22:54:02Z | 2023-12-21T20:59:20Z | 2023-12-21T20:59:20Z | 2024-02-14T01:30:52Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.