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

Code before:

        Returns
        -------
        GroupBy
            The return type of `func`.

        See Also
        --------
        Series.pipe : Apply a function with arguments to a series.
        DataFrame.pipe : Apply a function with arguments to a dataframe.
        apply : Apply function to each group instead of to the
            full GroupBy object.

        Notes
        -----
        See more `here
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`_

        Examples
        --------
        >>> df = pd.DataFrame({"A": "a b a b".split(), "B": [1, 2, 3, 4]})
        >>> df
        A  B
        0  a  1
        1  b  2
        2  a  3
        3  b  4

        To get the difference between each groups maximum and minimum value in one
        pass, you can do

        >>> df.groupby("A").pipe(lambda x: x.max() - x.min())
        B
        A
        a  2
        b  2
        """
        return com.pipe(self, func, *args, **kwargs)

    @final
    def get_group(self, name) -> DataFrame | Series:
        """
        Construct DataFrame from group with provided name.

        Parameters
        ----------
        name : object
            The name of the group to get as a DataFrame.

        Returns
        -------

Review comment (bug):
This change is wrong, the columns should be adjusted. Is pre-commit doing this with the ruff formater?

Code after:

        Returns
        -------
        GroupBy
            The return type of `func`.

        See Also
        --------
        Series.pipe : Apply a function with arguments to a series.
        DataFrame.pipe : Apply a function with arguments to a dataframe.
        apply : Apply function to each group instead of to the
            full GroupBy object.

        Notes
        -----
        See more `here
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`_

        Examples
        --------
        >>> df = pd.DataFrame({"A": "a b a b".split(), "B": [1, 2, 3, 4]})
        >>> df
           A  B
        0  a  1
        1  b  2
        2  a  3
        3  b  4

        To get the difference between each groups maximum and minimum value in one
        pass, you can do

        >>> df.groupby("A").pipe(lambda x: x.max() - x.min())
           B
        A
        a  2
        b  2
        """
        return com.pipe(self, func, *args, **kwargs)

    @final
    def get_group(self, name) -> DataFrame | Series:
        """
        Construct DataFrame from group with provided name.

        Parameters
        ----------
        name : object
            The name of the group to get as a DataFrame.

        Returns
        -------
Repository: pandas-dev/pandas
File: pandas/tests/frame/indexing/test_where.py (Python)

Code before:
    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)


def test_where_inplace_string_array_consistency():
    # GH#46512 - inplace and non-inplace should have consistent behavior
    # for StringArray with NA-like values
    df = DataFrame({"A": ["1", "", "3"]}, dtype="string")
    df_inplace = df.copy()

    # Test non-inplace
    result = df.where(df != "", np.nan)

    # Test inplace
    df_inplace.where(df_inplace != "", np.nan, inplace=True)

    # Both should produce pd.NA, not float nan
    assert isinstance(result["A"]._values[1], type(pd.NA))
    assert isinstance(df_inplace["A"]._values[1], type(pd.NA))

    # Results should be identical
    tm.assert_frame_equal(result, df_inplace)


Review comment (suggestion):
Please remove all comments (and below) except `GH#46512`

Code after:
    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)


def test_where_inplace_string_array_consistency():
    # GH#46512
    df = DataFrame({"A": ["1", "", "3"]}, dtype="string")
    df_inplace = df.copy()

    result = df.where(df != "", np.nan)
    df_inplace.where(df_inplace != "", np.nan, inplace=True)

    tm.assert_frame_equal(result, df_inplace)
Repository: pandas-dev/pandas
File: pandas/tests/test_col.py (Python)

Code before:
            pd.col("a") | False,
            [True, False, True, False],
            "(col('a') | False)",
        ),
        (
            pd.col("a") ^ pd.col("b"),
            [True, True, False, True],
            "(col('a') ^ col('b'))",
        ),
        (
            pd.col("a") ^ True,
            [False, True, False, True],
            "(col('a') ^ True)",
        ),
        (
            ~pd.col("a"),
            [False, True, False, True],
            "(~col('a'))",
        ),
    ],
)
def test_col_logical_ops(
    expr: Expression, expected_values: list[bool], expected_str: str
) -> None:
    df = pd.DataFrame({"a": [True, False, True, False], "b": [False, True, True, True]})
    result = df.assign(c=expr)
    expected = pd.DataFrame(
        {
            "a": [True, False, True, False],
            "b": [False, True, True, True],
            "c": expected_values,
        }
    )
    tm.assert_frame_equal(result, expected)
    assert str(expr) == expected_str

    # Test that the expression works with .loc
    result = df.loc[expr]
    expected = df[expected_values]
    tm.assert_frame_equal(result, expected)


Review comment (suggestion):
```suggestion
) -> None:
    # https://github.com/pandas-dev/pandas/issues/63322
    df = pd.DataFrame({"a": [True, False, True, False], "b": [False, True, True, True]})
```

Code after:
            pd.col("a") | False,
            [True, False, True, False],
            "(col('a') | False)",
        ),
        (
            pd.col("a") ^ pd.col("b"),
            [True, True, False, True],
            "(col('a') ^ col('b'))",
        ),
        (
            pd.col("a") ^ True,
            [False, True, False, True],
            "(col('a') ^ True)",
        ),
        (
            ~pd.col("a"),
            [False, True, False, True],
            "(~col('a'))",
        ),
    ],
)
def test_col_logical_ops(
    expr: Expression, expected_values: list[bool], expected_str: str
) -> None:
    # https://github.com/pandas-dev/pandas/issues/63322
    df = pd.DataFrame({"a": [True, False, True, False], "b": [False, True, True, True]})
    result = df.assign(c=expr)
    expected = pd.DataFrame(
        {
            "a": [True, False, True, False],
            "b": [False, True, True, True],
            "c": expected_values,
        }
    )
    tm.assert_frame_equal(result, expected)
    assert str(expr) == expected_str

    # Test that the expression works with .loc
    result = df.loc[expr]
    expected = df[expected_values]
    tm.assert_frame_equal(result, expected)
Repository: pandas-dev/pandas
File: pandas/core/groupby/generic.py (Python)

Code before:
        0 -1.154701 -0.577350
        1  0.577350  0.000000
        2  0.577350  1.154701
        3 -1.154701 -1.000000
        4  0.577350 -0.577350
        5  0.577350  1.000000

        Broadcast result of the transformation

        >>> grouped.transform(lambda x: x.max() - x.min())
            C    D
        0  4.0  6.0
        1  3.0  8.0
        2  4.0  6.0
        3  3.0  8.0
        4  4.0  6.0
        5  3.0  8.0

        >>> grouped.transform("mean")
            C        D
        0  3.666667  4.0
        1  4.000000  5.0
        2  3.666667  4.0
        3  4.000000  5.0
        4  3.666667  4.0
        5  4.000000  5.0

        The resulting dtype will reflect the return value of the passed ``func``,
        for example:

        >>> grouped.transform(lambda x: x.astype(int).max())
           C  D
        0  5  8
        1  5  9
        2  5  8
        3  5  9
        4  5  8
        5  5  9
        """
        return self._transform(
            func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
        )

    def _define_paths(self, func, *args, **kwargs):
        if isinstance(func, str):
            fast_path = lambda group: getattr(group, func)(*args, **kwargs)
            slow_path = lambda group: group.apply(
                lambda x: getattr(x, func)(*args, **kwargs), axis=0
            )
        else:
            fast_path = lambda group: func(group, *args, **kwargs)

Review comment (suggestion):
```suggestion
                  C    D
        0  3.666667  4.0
        1  4.000000  5.0
        2  3.666667  4.0
        3  4.000000  5.0
        4  3.666667  4.0
        5  4.000000  5.0
```

Code after:
        0 -1.154701 -0.577350
        1  0.577350  0.000000
        2  0.577350  1.154701
        3 -1.154701 -1.000000
        4  0.577350 -0.577350
        5  0.577350  1.000000

        Broadcast result of the transformation

        >>> grouped.transform(lambda x: x.max() - x.min())
             C    D
        0  4.0  6.0
        1  3.0  8.0
        2  4.0  6.0
        3  3.0  8.0
        4  4.0  6.0
        5  3.0  8.0

        >>> grouped.transform("mean")
                  C    D
        0  3.666667  4.0
        1  4.000000  5.0
        2  3.666667  4.0
        3  4.000000  5.0
        4  3.666667  4.0
        5  4.000000  5.0

        The resulting dtype will reflect the return value of the passed ``func``,
        for example:

        >>> grouped.transform(lambda x: x.astype(int).max())
           C  D
        0  5  8
        1  5  9
        2  5  8
        3  5  9
        4  5  8
        5  5  9
        """
        return self._transform(
            func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
        )

    def _define_paths(self, func, *args, **kwargs):
        if isinstance(func, str):
            fast_path = lambda group: getattr(group, func)(*args, **kwargs)
            slow_path = lambda group: group.apply(
                lambda x: getattr(x, func)(*args, **kwargs), axis=0
            )
        else:
            fast_path = lambda group: func(group, *args, **kwargs)
Repository: pandas-dev/pandas
File: pandas/core/tools/timedeltas.py (Python)

Code before:
        if errors == "raise":
            raise
        # coerce
        result = NaT

    return result


def _convert_listlike(
    arg,
    unit: UnitChoices | None = None,
    errors: DateTimeErrorChoices = "raise",
    name: Hashable | None = None,
):
    """Convert a list of objects to a timedelta index object."""
    arg_dtype = getattr(arg, "dtype", None)
    if isinstance(arg, (list, tuple)) or arg_dtype is None:
        arg = np.array(arg, dtype=object)
    elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
        return arg

    td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]

    from pandas import TimedeltaIndex

    value = TimedeltaIndex(td64arr, name=name, copy=False)
    return value


Review comment (bug):
This one in theory depends on the input, if we want `to_timedelta` similarly copy array input like the Index constructor.

With this branch:
```
>>> arr = np.array([1, 2, 3], dtype="timedelta64[ns]")
>>> idx = pd.to_timedelta(arr)
>>> idx
TimedeltaIndex(['0 days 00:00:00.000000001', '0 days 00:00:00.000000002',
                '0 days 00:00:00.000000003'],
               dtype='timedelta64[ns]', freq=None)
>>> arr[0] = 100
>>> idx
TimedeltaIndex(['0 days 00:00:00.000000100', '0 days 00:00:00.000000002',
                '0 days 00:00:00.000000003'],
               dtype='timedelta64[ns]', freq=None)
```

So `idx` got modified (incorrectly).

Maybe could check for `td64arr is arg` and in that case do copy? (of course, `to_timedelta` then has no way to disable the copy, but if you want that you can also use the Index constructor)

Code after:
        if errors == "raise":
            raise
        # coerce
        result = NaT

    return result


def _convert_listlike(
    arg,
    unit: UnitChoices | None = None,
    errors: DateTimeErrorChoices = "raise",
    name: Hashable | None = None,
):
    """Convert a list of objects to a timedelta index object."""
    arg_dtype = getattr(arg, "dtype", None)
    if isinstance(arg, (list, tuple)) or arg_dtype is None:
        arg = np.array(arg, dtype=object)
    elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
        return arg

    td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]

    from pandas import TimedeltaIndex

    copy = td64arr is arg or np.may_share_memory(arg, td64arr)
    value = TimedeltaIndex(td64arr, name=name, copy=copy)
    return value
Repository: pandas-dev/pandas
File: pandas/core/tools/timedeltas.py (Python)

Code before:
        if errors == "raise":
            raise
        # coerce
        result = NaT

    return result


def _convert_listlike(
    arg,
    unit: UnitChoices | None = None,
    errors: DateTimeErrorChoices = "raise",
    name: Hashable | None = None,
):
    """Convert a list of objects to a timedelta index object."""
    arg_dtype = getattr(arg, "dtype", None)
    if isinstance(arg, (list, tuple)) or arg_dtype is None:
        arg = np.array(arg, dtype=object)
    elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
        return arg

    td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]

    from pandas import TimedeltaIndex

    copy = td64arr is arg
    value = TimedeltaIndex(td64arr, name=name, copy=copy)
    return value


Review comment (suggestion):
```suggestion
    copy = td64arr is arg or np.may_share_memory(arg, td64arr)
```

Code after:
        if errors == "raise":
            raise
        # coerce
        result = NaT

    return result


def _convert_listlike(
    arg,
    unit: UnitChoices | None = None,
    errors: DateTimeErrorChoices = "raise",
    name: Hashable | None = None,
):
    """Convert a list of objects to a timedelta index object."""
    arg_dtype = getattr(arg, "dtype", None)
    if isinstance(arg, (list, tuple)) or arg_dtype is None:
        arg = np.array(arg, dtype=object)
    elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.kind == "m":
        return arg

    td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]

    from pandas import TimedeltaIndex

    copy = td64arr is arg or np.may_share_memory(arg, td64arr)
    value = TimedeltaIndex(td64arr, name=name, copy=copy)
    return value
Repository: pandas-dev/pandas
File: pandas/core/groupby/generic.py (Python)

Code before:
        lion     mammal       80.5
        monkey   mammal       21.5
        rabbit   mammal       15.0
        dog      mammal       40.0
        wolf     mammal       50.0
        >>> gb = df.groupby(["class"])
        >>> gb.kurt()
                max_speed
        class
        bird    -5.493277
        mammal   0.204125
        >>> gb.kurt(skipna=False)
                max_speed
        class
        bird          NaN
        mammal   0.204125
        """

        return self._cython_agg_general(
            "kurt", alt=None, skipna=skipna, numeric_only=numeric_only, **kwargs
        )

    @property
    def plot(self) -> GroupByPlot:
        """
        Make plots of DataFrameGroupBy.

        Uses the backend specified by the option ``plotting.backend``.
        By default, matplotlib is used.

        Returns
        -------
        GroupByPlot
            A plotting object that can be used to create plots for each group.

        See Also
        --------
        DataFrame.plot : Make plots of DataFrame.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=["a", "a", "b", "b"]
        ... )
        >>> g = df.groupby(level=0)
        >>> g.plot()  # doctest: +SKIP
        """
        result = GroupByPlot(self)
        return result

    @doc(DataFrame.corr.__doc__)

Review comment (suggestion):
```suggestion
        Make plots of groups from a DataFrame.
```

Code after:
        lion     mammal       80.5
        monkey   mammal       21.5
        rabbit   mammal       15.0
        dog      mammal       40.0
        wolf     mammal       50.0
        >>> gb = df.groupby(["class"])
        >>> gb.kurt()
                max_speed
        class
        bird    -5.493277
        mammal   0.204125
        >>> gb.kurt(skipna=False)
                max_speed
        class
        bird          NaN
        mammal   0.204125
        """

        return self._cython_agg_general(
            "kurt", alt=None, skipna=skipna, numeric_only=numeric_only, **kwargs
        )

    @property
    def plot(self) -> GroupByPlot:
        """
        Make plots of groups from a DataFrame.

        Uses the backend specified by the option ``plotting.backend``.
        By default, matplotlib is used.

        Returns
        -------
        GroupByPlot
            A plotting object that can be used to create plots for each group.

        See Also
        --------
        DataFrame.plot : Make plots of DataFrame.

        Examples
        --------
        >>> df = pd.DataFrame(
        ...     {"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=["a", "a", "b", "b"]
        ... )
        >>> g = df.groupby(level=0)
        >>> g.plot()  # doctest: +SKIP
        """
        result = GroupByPlot(self)
        return result

    @doc(DataFrame.corr.__doc__)
Repository: pandas-dev/pandas
File: pandas/tests/dtypes/test_concat.py (Python)

Code before:
import datetime as dt

import numpy as np
import pytest

import pandas.core.dtypes.concat as _concat

import pandas as pd
from pandas import Series
import pandas._testing as tm


def test_concat_mismatched_categoricals_with_empty():
    # concat_compat behavior on series._values should match pd.concat on series
    ser1 = Series(["a", "b", "c"], dtype="category")
    ser2 = Series([], dtype="category")

    result = _concat.concat_compat([ser1._values, ser2._values])
    expected = pd.concat([ser1, ser2])._values
    tm.assert_numpy_array_equal(result, expected)


def test_concat_single_dataframe_tz_aware():
    # https://github.com/pandas-dev/pandas/issues/25257
    df = pd.DataFrame(
        {"timestamp": [pd.Timestamp("2020-04-08 09:00:00.709949+0000", tz="UTC")]}

Review comment (suggestion):
```suggestion
import datetime
```

IMO it's a lot clearer just to not shorten this

Code after:
import pytest

import pandas.core.dtypes.concat as _concat

import pandas as pd
from pandas import Series
import pandas._testing as tm


def test_concat_mismatched_categoricals_with_empty():
    # concat_compat behavior on series._values should match pd.concat on series
    ser1 = Series(["a", "b", "c"], dtype="category")
    ser2 = Series([], dtype="category")

    result = _concat.concat_compat([ser1._values, ser2._values])
    expected = pd.concat([ser1, ser2])._values
    tm.assert_numpy_array_equal(result, expected)


def test_concat_single_dataframe_tz_aware():
    # https://github.com/pandas-dev/pandas/issues/25257
    df = pd.DataFrame(
        {"timestamp": [pd.Timestamp("2020-04-08 09:00:00.709949+0000", tz="UTC")]}
    )
    expected = df.copy()
    result = pd.concat([df])
Repository: pandas-dev/pandas
File: pandas/tests/indexing/test_indexers.py (Python)

Code before:


def test_length_of_indexer():
    arr = np.zeros(4, dtype=bool)
    arr[0] = 1
    result = length_of_indexer(arr)
    assert result == 1


@pytest.mark.parametrize(
    "start,stop,step",
    [
        (0, 10**30, 2),
        (10**30, 0, -3),
    ],
)
def test_length_of_indexer_range_overflow(start, stop, step):
    indexer = range(start, stop, step)
    result = length_of_indexer(indexer)
    step_ = step
    if step_ > 0:
        low, high = start, stop
    else:
        low, high = stop, start
        step_ = -step_
    expected = 0 if low >= high else (high - low - 1) // step_ + 1
    assert result == expected


def test_is_scalar_indexer():
    indexer = (0, 1)
    assert is_scalar_indexer(indexer, 2)
    assert not is_scalar_indexer(indexer[0], 2)

    indexer = (np.array([2]), 1)
    assert not is_scalar_indexer(indexer, 2)

    indexer = (np.array([2]), np.array([3]))
    assert not is_scalar_indexer(indexer, 2)

    indexer = (np.array([2]), np.array([3, 4]))
    assert not is_scalar_indexer(indexer, 2)

    assert not is_scalar_indexer(slice(None), 1)

    indexer = 0
    assert is_scalar_indexer(indexer, 1)

    indexer = (0,)
    assert is_scalar_indexer(indexer, 1)


Review comment (suggestion):
Instead of duplicating the formula, can you hardcode the correct `expected` as part of the parameters.

Code after:


def test_length_of_indexer():
    arr = np.zeros(4, dtype=bool)
    arr[0] = 1
    result = length_of_indexer(arr)
    assert result == 1


@pytest.mark.parametrize(
    "start, stop, step, expected",
    [
        (10, 0, -3, 4),
        (0, 1, 5, 1),
    ],
)
def test_length_of_indexer_range_overflow(start, stop, step, expected):
    # https://github.com/pandas-dev/pandas/pull/63872
    indexer = range(start, stop, step)
    result = length_of_indexer(indexer)
    assert result == expected


def test_is_scalar_indexer():
    indexer = (0, 1)
    assert is_scalar_indexer(indexer, 2)
    assert not is_scalar_indexer(indexer[0], 2)

    indexer = (np.array([2]), 1)
    assert not is_scalar_indexer(indexer, 2)

    indexer = (np.array([2]), np.array([3]))
    assert not is_scalar_indexer(indexer, 2)

    indexer = (np.array([2]), np.array([3, 4]))
    assert not is_scalar_indexer(indexer, 2)

    assert not is_scalar_indexer(slice(None), 1)

    indexer = 0
    assert is_scalar_indexer(indexer, 1)

    indexer = (0,)
    assert is_scalar_indexer(indexer, 1)


class TestValidateIndices:
    def test_validate_indices_ok(self):
        indices = np.asarray([0, 1])
        validate_indices(indices, 2)
        validate_indices(indices[:0], 0)