ronantakizawa/codereview-bench huggingface dataset:
Repository: pandas-dev/pandas
File: pandas/core/arrays/boolean.py (Python)

Code before:
from pandas.core.array_algos import masked_accumulations
from pandas.core.arrays.masked import (
    BaseMaskedArray,
    BaseMaskedDtype,
)

if TYPE_CHECKING:
    import pyarrow

    from pandas._typing import (
        DtypeObj,
        npt,
        type_t,
    )

    from pandas.core.dtypes.dtypes import ExtensionDtype


@register_extension_dtype
@set_module("pandas")
class BooleanDtype(BaseMaskedDtype):
    """
    Extension dtype for boolean data.

    This is a pandas Extension dtype for boolean data with support for
    missing values. BooleanDtype is the dtype companion to :class:`BooleanArray`,
    which implements Kleene logic (sometimes called three-value logic) for
    logical operations. See :ref:`boolean.kleene` for more.

    .. warning::

        BooleanDtype is considered experimental. The implementation and
        parts of the API may change without warning.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    BooleanArray : Array of boolean (True/False) data with missing values.
    Int64Dtype : Extension dtype for int64 integer data.
    StringDtype : Extension dtype for string data.

    Examples
    --------
    >>> pd.BooleanDtype()

Review comment (suggestion):
This won't link to the BooleanArray page because `pd.BooleanArray` does not exist, it's `pd.arrays.BooleanArray`. By adding the `.`, sphinx will search and find `BooleanArray`.

```suggestion
    missing values. BooleanDtype is the dtype companion to :class:`.BooleanArray`,
```

Code after:
from pandas.core.array_algos import masked_accumulations
from pandas.core.arrays.masked import (
    BaseMaskedArray,
    BaseMaskedDtype,
)

if TYPE_CHECKING:
    import pyarrow

    from pandas._typing import (
        DtypeObj,
        npt,
        type_t,
    )

    from pandas.core.dtypes.dtypes import ExtensionDtype


@register_extension_dtype
@set_module("pandas")
class BooleanDtype(BaseMaskedDtype):
    """
    Extension dtype for boolean data.

    This is a pandas Extension dtype for boolean data with support for
    missing values. BooleanDtype is the dtype companion to :class:`.BooleanArray`,
    which implements Kleene logic (sometimes called three-value logic) for
    logical operations. See :ref:`boolean.kleene` for more.

    .. warning::

        BooleanDtype is considered experimental. The implementation and
        parts of the API may change without warning.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    arrays.BooleanArray : Array of boolean (True/False) data with missing values.
    Int64Dtype : Extension dtype for int64 integer data.
    StringDtype : Extension dtype for string data.

    Examples
    --------
    >>> pd.BooleanDtype()
Repository: pandas-dev/pandas
File: pandas/core/arrays/boolean.py (Python)

Code before:
@set_module("pandas")
class BooleanDtype(BaseMaskedDtype):
    """
    Extension dtype for boolean data.

    This is a pandas Extension dtype for boolean data with support for
    missing values. BooleanDtype is the dtype companion to :class:`BooleanArray`,
    which implements Kleene logic (sometimes called three-value logic) for
    logical operations. See :ref:`boolean.kleene` for more.

    .. warning::

        BooleanDtype is considered experimental. The implementation and
        parts of the API may change without warning.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    BooleanArray : Array of boolean (True/False) data with missing values.
    Int64Dtype : Extension dtype for int64 integer data.
    StringDtype : Extension dtype for string data.

    Examples
    --------
    >>> pd.BooleanDtype()
    BooleanDtype

    >>> pd.array([True, False, None], dtype=pd.BooleanDtype())
    <BooleanArray>
    [True, False, <NA>]
    Length: 3, dtype: boolean

    >>> pd.array([True, False, None], dtype="boolean")
    <BooleanArray>
    [True, False, <NA>]
    Length: 3, dtype: boolean
    """

    name: ClassVar[str] = "boolean"

    # The value used to fill '_data' to avoid upcasting
    _internal_fill_value = False

    # https://github.com/python/mypy/issues/4125

Review comment (suggestion):
Similarly here, except you can't just use a `.`.

```suggestion
    arrays.BooleanArray : Array of boolean (True/False) data with missing values.
```

Code after:
@set_module("pandas")
class BooleanDtype(BaseMaskedDtype):
    """
    Extension dtype for boolean data.

    This is a pandas Extension dtype for boolean data with support for
    missing values. BooleanDtype is the dtype companion to :class:`.BooleanArray`,
    which implements Kleene logic (sometimes called three-value logic) for
    logical operations. See :ref:`boolean.kleene` for more.

    .. warning::

        BooleanDtype is considered experimental. The implementation and
        parts of the API may change without warning.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    arrays.BooleanArray : Array of boolean (True/False) data with missing values.
    Int64Dtype : Extension dtype for int64 integer data.
    StringDtype : Extension dtype for string data.

    Examples
    --------
    >>> pd.BooleanDtype()
    BooleanDtype

    >>> pd.array([True, False, None], dtype=pd.BooleanDtype())
    <BooleanArray>
    [True, False, <NA>]
    Length: 3, dtype: boolean

    >>> pd.array([True, False, None], dtype="boolean")
    <BooleanArray>
    [True, False, <NA>]
    Length: 3, dtype: boolean
    """

    name: ClassVar[str] = "boolean"

    # The value used to fill '_data' to avoid upcasting
    _internal_fill_value = False

    # https://github.com/python/mypy/issues/4125
Repository: pandas-dev/pandas
File: pandas/tests/frame/methods/test_convert_dtypes.py (Python)

Code before:
        df = pd.DataFrame([["a", datetime.time(18, 12)]], columns=["a", "b"])
        result = df.convert_dtypes()
        expected = df.astype({"a": "string"})
        tm.assert_frame_equal(result, expected)

    def test_convert_dtype_pyarrow_timezone_preserve(self):
        # GH 60237
        pytest.importorskip("pyarrow")
        df = pd.DataFrame(
            {
                "timestamps": pd.Series(
                    pd.to_datetime(range(5), utc=True, unit="h"),
                    dtype="timestamp[ns, tz=UTC][pyarrow]",
                )
            }
        )
        result = df.convert_dtypes(dtype_backend="pyarrow")
        expected = df.copy()
        tm.assert_frame_equal(result, expected)

    def test_convert_dtypes_complex(self):
        # GH 60129
        df = pd.DataFrame({"a": [1.0 + 5.0j, 1.5 - 3.0j]})
        result = df.convert_dtypes()
        tm.assert_frame_equal(result, df)
        assert result["a"].dtype.kind == "c"


Review comment (suggestion):
This is not necessary, dtypes are checked in `assert_frame_equal`. Can you remove.

Code after:
        df = pd.DataFrame([["a", datetime.time(18, 12)]], columns=["a", "b"])
        result = df.convert_dtypes()
        expected = df.astype({"a": "string"})
        tm.assert_frame_equal(result, expected)

    def test_convert_dtype_pyarrow_timezone_preserve(self):
        # GH 60237
        pytest.importorskip("pyarrow")
        df = pd.DataFrame(
            {
                "timestamps": pd.Series(
                    pd.to_datetime(range(5), utc=True, unit="h"),
                    dtype="timestamp[ns, tz=UTC][pyarrow]",
                )
            }
        )
        result = df.convert_dtypes(dtype_backend="pyarrow")
        expected = df.copy()
        tm.assert_frame_equal(result, expected)

    def test_convert_dtypes_complex(self):
        # GH 60129
        df = pd.DataFrame({"a": [1.0 + 5.0j, 1.5 - 3.0j], "b": [1, 2]})
        expected = pd.DataFrame(
            {
                "a": pd.array([1.0 + 5.0j, 1.5 - 3.0j], dtype="complex128"),
                "b": pd.array([1, 2], dtype="Int64"),
            }
        )
        result = df.convert_dtypes()
        tm.assert_frame_equal(result, expected)
Repository: pandas-dev/pandas
File: pandas/core/internals/managers.py (Python)

Code before:
        if index is not None:
            axes[-1] = index
        axes[0] = self.items.take(indexer)

        return type(self).from_blocks(new_blocks, axes)

    @property
    def nblocks(self) -> int:
        return len(self.blocks)

    def copy(self, *, deep: bool) -> Self:
        """
        Make deep or shallow copy of BlockManager

        Parameters
        ----------
        deep : bool, string or None, default True
            If False or None, return a shallow copy (do not copy data)
            If 'all', copy data and a deep copy of the index

        Returns
        -------
        BlockManager
        """
        # this preserves the notion of view copying of axes
        new_axes = [ax.view() for ax in self.axes]

        res = self.apply("copy", deep=deep)
        res.axes = new_axes

        if self.ndim > 1:
            # Avoid needing to re-compute these
            blknos = self._blknos
            if blknos is not None:
                res._blknos = blknos.copy()
                res._blklocs = self._blklocs.copy()

        if deep:
            res._consolidate_inplace()
        return res

    def is_consolidated(self) -> bool:
        return True

    def consolidate(self) -> Self:
        """
        Join together blocks having same dtype

        Returns
        -------
        y : BlockManager

Review comment (suggestion):
Reason that this is removed?

I know that an Index is generally immutable so the difference between view or actual copy is not relevant when it comes to the _data_, but we still some mutable _attributes_

Code after:
        if index is not None:
            axes[-1] = index
        axes[0] = self.items.take(indexer)

        return type(self).from_blocks(new_blocks, axes)

    @property
    def nblocks(self) -> int:
        return len(self.blocks)

    def copy(self, *, deep: bool) -> Self:
        """
        Make deep or shallow copy of BlockManager

        Parameters
        ----------
        deep : bool, string or None, default True
            If False, return a shallow copy (do not copy data)

        Returns
        -------
        BlockManager
        """
        # TODO: Should deep=True be respected for axes?
        new_axes = [ax.view() for ax in self.axes]

        res = self.apply("copy", deep=deep)
        res.axes = new_axes

        if self.ndim > 1:
            # Avoid needing to re-compute these
            blknos = self._blknos
            if blknos is not None:
                res._blknos = blknos.copy()
                res._blklocs = self._blklocs.copy()

        if deep:
            res._consolidate_inplace()
        return res

    def is_consolidated(self) -> bool:
        return True

    def consolidate(self) -> Self:
        """
        Join together blocks having same dtype

        Returns
        -------
        y : BlockManager
        """
Repository: pandas-dev/pandas
File: pandas/tests/indexes/interval/test_interval_range.py (Python)

Code before:
        with pytest.raises(ValueError, match=msg):
            interval_range(start=Timestamp("20130101"), periods=10, freq="foo")

        with pytest.raises(ValueError, match=msg):
            interval_range(end=Timedelta("1 day"), periods=10, freq="foo")

        # mixed tz
        start = Timestamp("2017-01-01", tz="US/Eastern")
        end = Timestamp("2017-01-07", tz="US/Pacific")
        msg = "Start and end cannot both be tz-aware with different timezones"
        with pytest.raises(TypeError, match=msg):
            interval_range(start=start, end=end)

    def test_float_freq(self):
        # GH 54477
        result = interval_range(0, 1, freq=0.1)
        expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])
        tm.assert_index_equal(result, expected)

        result = interval_range(0, 1, freq=0.6)
        expected = IntervalIndex.from_breaks([0, 0.6])
        tm.assert_index_equal(result, expected)

    def test_interval_range_float32_start_int_freq(self):
        # GH 58964
        from pandas.testing import assert_index_equal

        result = interval_range(start=np.float32(0), end=2, freq=1)
        expected = IntervalIndex.from_tuples(
            [(0.0, 1.0), (1.0, 2.0)], dtype="interval[float64, right]"
        )
        assert_index_equal(result, expected)


Review comment (suggestion):
```suggestion
```
You can use `tm` from the top level import

Code after:
        with pytest.raises(ValueError, match=msg):
            interval_range(start=Timestamp("20130101"), periods=10, freq="foo")

        with pytest.raises(ValueError, match=msg):
            interval_range(end=Timedelta("1 day"), periods=10, freq="foo")

        # mixed tz
        start = Timestamp("2017-01-01", tz="US/Eastern")
        end = Timestamp("2017-01-07", tz="US/Pacific")
        msg = "Start and end cannot both be tz-aware with different timezones"
        with pytest.raises(TypeError, match=msg):
            interval_range(start=start, end=end)

    def test_float_freq(self):
        # GH 54477
        result = interval_range(0, 1, freq=0.1)
        expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])
        tm.assert_index_equal(result, expected)

        result = interval_range(0, 1, freq=0.6)
        expected = IntervalIndex.from_breaks([0, 0.6])
        tm.assert_index_equal(result, expected)

    def test_interval_range_float32_start_int_freq(self):
        # GH 58964
        result = interval_range(start=np.float32(0), end=2, freq=1)
        expected = IntervalIndex.from_tuples(
            [(0.0, 1.0), (1.0, 2.0)], dtype="interval[float64, right]"
        )
        tm.assert_index_equal(result, expected)
Repository: pandas-dev/pandas
File: pandas/tests/io/pytables/test_keys.py (Python)

Code before:
import numpy as np
import pytest

from pandas import (
    DataFrame,
    HDFStore,
    Index,
    Series,
    date_range,
)
from pandas.tests.io.pytables.common import (
    tables
)

pytestmark = [pytest.mark.single_cpu]


def test_keys(tmp_path):
    path = tmp_path / "test_keys.h5"
    with HDFStore(path) as store:
        store["a"] = Series(
            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
        )
        store["b"] = Series(
            range(10), dtype="float64", index=[f"i_{i}" for i in range(10)]
        )
        store["c"] = DataFrame(
            1.1 * np.arange(120).reshape((30, 4)),
            columns=Index(list("ABCD"), dtype=object),
            index=Index([f"i-{i}" for i in range(30)], dtype=object),
        )

        assert len(store) == 3
        expected = {"/a", "/b", "/c"}
        assert set(store.keys()) == expected
        assert set(store) == expected


Review comment (suggestion):
It should be

```python
from pandas.tests.io.pytables.common import tables
```

See the [pre-commit](https://pandas.pydata.org/docs/development/contributing_codebase.html#contributing-pre-commit) section for how to run code checks. It will catch errors like this.


Code after:
import numpy as np
import pytest

from pandas import (
    DataFrame,
    HDFStore,
    Index,
    Series,
    date_range,
)
from pandas.tests.io.pytables.common import tables

pytestmark = [pytest.mark.single_cpu]


def test_keys(tmp_path):
    path = tmp_path / "test_keys.h5"
    with HDFStore(path) as store:
        store["a"] = Series(
            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
        )
        store["b"] = Series(
            range(10), dtype="float64", index=[f"i_{i}" for i in range(10)]
        )
        store["c"] = DataFrame(
            1.1 * np.arange(120).reshape((30, 4)),
            columns=Index(list("ABCD"), dtype=object),
            index=Index([f"i-{i}" for i in range(30)], dtype=object),
        )

        assert len(store) == 3
        expected = {"/a", "/b", "/c"}
        assert set(store.keys()) == expected
        assert set(store) == expected


def test_non_pandas_keys(tmp_path, setup_path):
Repository: pandas-dev/pandas
File: pandas/tests/groupby/test_apply.py (Python)

Code before:
        x["rank"] = x.val.rank(method="min")
        return x.groupby("cat2")["rank"].min()

    expected = DataFrame(
        {
            "cat1": list("aaaabbb"),
            "cat2": list("cdefcde"),
            "rank": [3.0, 2.0, 5.0, 1.0, 2.0, 4.0, 1.0],
        }
    ).set_index(["cat1", "cat2"])["rank"]
    result = df.groupby("cat1").apply(f)
    tm.assert_series_equal(result, expected)


def test_groupby_apply_store_copy():
    # GH40673
    rng = np.random.default_rng(seed=42)

    df = DataFrame(
        {
            "A": rng.normal(10, 12, size=(4,)),
            "B": [1, 2, 1, 2],
        }
    )

    # Empty dict to hold the chunks
    store = {}

    def addstore(x):
        store[len(store)] = x.copy()

    df.groupby("B").apply(addstore)

    # Output boolean mask
    out_mask = {0: [True, False, True, False], 1: [False, True, False, True]}

    # The expected output in store dict
    expected_out = {0: df[out_mask[0]], 1: df[out_mask[1]]}

    tm.assert_frame_equal(store[0], expected_out[0].drop("B", axis=1))
    tm.assert_frame_equal(store[1], expected_out[1].drop("B", axis=1))


Review comment (suggestion):
This comment and the ones below don't add anything that isn't already in the code. Can you remove them.

Code after:
        x["rank"] = x.val.rank(method="min")
        return x.groupby("cat2")["rank"].min()

    expected = DataFrame(
        {
            "cat1": list("aaaabbb"),
            "cat2": list("cdefcde"),
            "rank": [3.0, 2.0, 5.0, 1.0, 2.0, 4.0, 1.0],
        }
    ).set_index(["cat1", "cat2"])["rank"]
    result = df.groupby("cat1").apply(f)
    tm.assert_series_equal(result, expected)


def test_groupby_apply_store_copy():
    # GH40673
    rng = np.random.default_rng(seed=42)

    df = DataFrame(
        {
            "A": rng.normal(10, 12, size=(4,)),
            "B": [1, 2, 1, 2],
        }
    )

    store = {}

    def addstore(x):
        store[len(store)] = x.copy()

    df.groupby("B").apply(addstore)

    expected_out_0 = df.iloc[[0, 2], [0]]
    expected_out_1 = df.iloc[[1, 3], [0]]

    tm.assert_frame_equal(store[0], expected_out_0)
    tm.assert_frame_equal(store[1], expected_out_1)
Repository: pandas-dev/pandas
File: pandas/tests/frame/indexing/test_where.py (Python)

Code before:
@pytest.mark.parametrize(
    "replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)]
)
def test_where_int_overflow(replacement):
    # GH 31687
    df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]])
    result = df.where(pd.notnull(df), replacement)
    expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]])

    tm.assert_frame_equal(result, expected)


def test_where_inplace_no_other():
    # GH#51685
    df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
    cond = DataFrame({"a": [True, False], "b": [False, True]})
    result = df.where(cond, inplace=True)
    assert result is df
    expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]})
    tm.assert_frame_equal(df, expected)


def test_where_other_nullable_dtype():
    # GH#49052 DataFrame.where should return nullable dtype when
    # other is a Series with nullable dtype, matching Series.where behavior
    df = Series([1, 2, 3], dtype="int64").to_frame()
    other = Series([pd.NA, pd.NA, pd.NA], dtype="Int64")
    result = df.where(df > 1, other, axis=0)
    expected = DataFrame({0: Series([pd.NA, 2, 3], dtype="Int64")})
    tm.assert_frame_equal(result, expected)


Review comment (suggestion):
```suggestion
    df = DataFrame([1, 2, 3], dtype="int64")
```

Code after:
@pytest.mark.parametrize(
    "replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)]
)
def test_where_int_overflow(replacement):
    # GH 31687
    df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]])
    result = df.where(pd.notnull(df), replacement)
    expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]])

    tm.assert_frame_equal(result, expected)


def test_where_inplace_no_other():
    # GH#51685
    df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
    cond = DataFrame({"a": [True, False], "b": [False, True]})
    result = df.where(cond, inplace=True)
    assert result is df
    expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]})
    tm.assert_frame_equal(df, expected)


def test_where_other_nullable_dtype():
    # GH#49052 DataFrame.where should return nullable dtype when
    # other is a Series with nullable dtype, matching Series.where behavior
    df = DataFrame([1, 2, 3], dtype="int64")
    other = Series([pd.NA, pd.NA, pd.NA], dtype="Int64")
    result = df.where(df > 1, other, axis=0)
    expected = DataFrame({0: Series([pd.NA, 2, 3], dtype="Int64")})
    tm.assert_frame_equal(result, expected)
Repository: pandas-dev/pandas
File: pandas/tests/tseries/frequencies/test_inference.py (Python)

Code before:


@td.skip_if_no("pyarrow")
def test_infer_freq_pyarrow():
    # GH#58403
    data = ["2022-01-01T10:00:00", "2022-01-01T10:00:30", "2022-01-01T10:01:00"]
    pd_series = Series(data).astype("timestamp[s][pyarrow]")
    pd_index = Index(data).astype("timestamp[s][pyarrow]")

    assert frequencies.infer_freq(pd_index.values) == "30s"
    assert frequencies.infer_freq(pd_series.values) == "30s"
    assert frequencies.infer_freq(pd_index) == "30s"
    assert frequencies.infer_freq(pd_series) == "30s"


def test_infer_freq_no_stateful_behavior():
    # GH#55794 infer_freq should not have stateful behavior
    # calling infer_freq on a full index with duplicates should not
    # affect the result of calling it on a slice without duplicates
    times = to_datetime(["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-03"])

    # Before calling infer_freq on full index
    assert frequencies.infer_freq(times[:3]) == "D"

    # Call on full index (which has duplicates, so returns None)
    frequencies.infer_freq(times)

    # After calling on full index, slice should still return "D"
    assert frequencies.infer_freq(times[:3]) == "D"


Review comment (suggestion):
```suggestion
    assert frequencies.infer_freq(times) is None
```

Code after:
def test_infer_freq_pyarrow():
    # GH#58403
    data = ["2022-01-01T10:00:00", "2022-01-01T10:00:30", "2022-01-01T10:01:00"]
    pd_series = Series(data).astype("timestamp[s][pyarrow]")
    pd_index = Index(data).astype("timestamp[s][pyarrow]")

    assert frequencies.infer_freq(pd_index.values) == "30s"
    assert frequencies.infer_freq(pd_series.values) == "30s"
    assert frequencies.infer_freq(pd_index) == "30s"
    assert frequencies.infer_freq(pd_series) == "30s"


def test_infer_freq_no_stateful_behavior():
    # GH#55794 infer_freq should not have stateful behavior
    # calling infer_freq on a full index with duplicates should not
    # affect the result of calling it on a slice without duplicates
    times = to_datetime(["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-03"])

    # Before calling infer_freq on full index
    assert frequencies.infer_freq(times[:3]) == "D"

    # Call on full index (which has duplicates, so returns None)
    assert frequencies.infer_freq(times) is None

    # After calling on full index, slice should still return "D"
    assert frequencies.infer_freq(times[:3]) == "D"