The following issues were found

pandas/tests/apply/test_series_transform.py
6 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

from pandas import (
    DataFrame,
    MultiIndex,
    Series,
    concat,
)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

from pandas import (
    DataFrame,
    MultiIndex,
    Series,
    concat,
)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

                      ([np.abs, np.sqrt], ["absolute", "sqrt"]),
        (np.array([np.sqrt]), ["sqrt"]),
        (np.array([np.abs, np.sqrt]), ["absolute", "sqrt"]),
    ],
)
def test_transform_listlike(string_series, ops, names):
    # GH 35964
    with np.errstate(all="ignore"):
        expected = concat([op(string_series) for op in ops], axis=1)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 32 Column: 1

              

@pytest.mark.parametrize("box", [dict, Series])
def test_transform_dictlike(string_series, box):
    # GH 35964
    with np.errstate(all="ignore"):
        expected = concat([np.sqrt(string_series), np.abs(string_series)], axis=1)
    expected.columns = ["foo", "bar"]
    result = string_series.transform(box({"foo": np.sqrt, "bar": np.abs}))

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 41 Column: 1

                  tm.assert_frame_equal(result, expected)


def test_transform_dictlike_mixed():
    # GH 40018 - mix of lists and non-lists in values of a dictionary
    df = Series([1, 4])
    result = df.transform({"b": ["sqrt", "abs"], "c": "sqrt"})
    expected = DataFrame(
        [[1.0, 1, 1.0], [2.0, 4, 2.0]],

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 43 Column: 5

              
def test_transform_dictlike_mixed():
    # GH 40018 - mix of lists and non-lists in values of a dictionary
    df = Series([1, 4])
    result = df.transform({"b": ["sqrt", "abs"], "c": "sqrt"})
    expected = DataFrame(
        [[1.0, 1, 1.0], [2.0, 4, 2.0]],
        columns=MultiIndex([("b", "c"), ("sqrt", "abs")], [(0, 0, 1), (0, 1, 0)]),
    )

            

Reported by Pylint.

pandas/core/ops/common.py
6 issues
No name 'lib' in module 'pandas._libs'
Error

Line: 7 Column: 1

              from functools import wraps
from typing import Callable

from pandas._libs.lib import item_from_zerodim
from pandas._typing import F

from pandas.core.dtypes.generic import (
    ABCDataFrame,
    ABCIndex,

            

Reported by Pylint.

Unable to import 'pandas._libs.lib'
Error

Line: 7 Column: 1

              from functools import wraps
from typing import Callable

from pandas._libs.lib import item_from_zerodim
from pandas._typing import F

from pandas.core.dtypes.generic import (
    ABCDataFrame,
    ABCIndex,

            

Reported by Pylint.

TODO: what if they both have np.nan for their names?
Error

Line: 122 Column: 3

                      if a.name == b.name:
            return a.name
        else:
            # TODO: what if they both have np.nan for their names?
            return None
    elif a_has:
        return a.name
    elif b_has:
        return b.name

            

Reported by Pylint.

Argument name "a" doesn't conform to snake_case naming style
Error

Line: 96 Column: 1

                  return name


def _maybe_match_name(a, b):
    """
    Try to find a name to attach to the result of an operation between
    a and b.  If only one of these has a `name` attribute, return that
    name.  Otherwise return a consensus name if they match or None if
    they have different names.

            

Reported by Pylint.

Argument name "b" doesn't conform to snake_case naming style
Error

Line: 96 Column: 1

                  return name


def _maybe_match_name(a, b):
    """
    Try to find a name to attach to the result of an operation between
    a and b.  If only one of these has a `name` attribute, return that
    name.  Otherwise return a consensus name if they match or None if
    they have different names.

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 119 Column: 9

                  a_has = hasattr(a, "name")
    b_has = hasattr(b, "name")
    if a_has and b_has:
        if a.name == b.name:
            return a.name
        else:
            # TODO: what if they both have np.nan for their names?
            return None
    elif a_has:

            

Reported by Pylint.

pandas/tests/arithmetic/test_categorical.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

from pandas import (
    Categorical,
    Series,
)
import pandas._testing as tm



            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 10 Column: 1

              import pandas._testing as tm


class TestCategoricalComparisons:
    def test_categorical_nan_equality(self):
        cat = Series(Categorical(["a", "b", "c", np.nan]))
        expected = Series([True, True, True, False])
        result = cat == cat
        tm.assert_series_equal(result, expected)

            

Reported by Pylint.

Missing class docstring
Error

Line: 10 Column: 1

              import pandas._testing as tm


class TestCategoricalComparisons:
    def test_categorical_nan_equality(self):
        cat = Series(Categorical(["a", "b", "c", np.nan]))
        expected = Series([True, True, True, False])
        result = cat == cat
        tm.assert_series_equal(result, expected)

            

Reported by Pylint.

Method could be a function
Error

Line: 11 Column: 5

              

class TestCategoricalComparisons:
    def test_categorical_nan_equality(self):
        cat = Series(Categorical(["a", "b", "c", np.nan]))
        expected = Series([True, True, True, False])
        result = cat == cat
        tm.assert_series_equal(result, expected)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 11 Column: 5

              

class TestCategoricalComparisons:
    def test_categorical_nan_equality(self):
        cat = Series(Categorical(["a", "b", "c", np.nan]))
        expected = Series([True, True, True, False])
        result = cat == cat
        tm.assert_series_equal(result, expected)

            

Reported by Pylint.

Redundant comparison - cat == cat
Error

Line: 14 Column: 18

                  def test_categorical_nan_equality(self):
        cat = Series(Categorical(["a", "b", "c", np.nan]))
        expected = Series([True, True, True, False])
        result = cat == cat
        tm.assert_series_equal(result, expected)

            

Reported by Pylint.

pandas/core/indexes/api.py
6 issues
No name 'lib' in module 'pandas._libs'
Error

Line: 5 Column: 1

              
import textwrap

from pandas._libs import (
    NaT,
    lib,
)
from pandas.errors import InvalidIndexError


            

Reported by Pylint.

Access to a protected member _get_axis of a client class
Error

Line: 95 Column: 18

                  -------
    Index
    """
    obs_idxes = [obj._get_axis(axis) for obj in objs]
    return _get_combined_index(obs_idxes, intersect=intersect, sort=sort, copy=copy)


def _get_distinct_objs(objs: list[Index]) -> list[Index]:
    """

            

Reported by Pylint.

TODO: handle index names!
Error

Line: 138 Column: 3

                  -------
    Index
    """
    # TODO: handle index names!
    indexes = _get_distinct_objs(indexes)
    if len(indexes) == 0:
        index = Index([])
    elif len(indexes) == 1:
        index = indexes[0]

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import annotations

import textwrap

from pandas._libs import (
    NaT,
    lib,
)
from pandas.errors import InvalidIndexError

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 216 Column: 9

                  if kind == "special":
        result = indexes[0]

        if hasattr(result, "union_many"):
            # DatetimeIndex
            return result.union_many(indexes[1:])
        else:
            for other in indexes[1:]:
                result = result.union(other)

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 268 Column: 5

                      else:
            return indexes, "list"

    if len(kinds) > 1 or Index not in kinds:
        return indexes, "special"
    else:
        return indexes, "array"



            

Reported by Pylint.

pandas/tests/arrays/boolean/test_repr.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              import pandas as pd


def test_repr():
    df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
    expected = "       A\n0   True\n1  False\n2   <NA>"
    assert repr(df) == expected

    expected = "0     True\n1    False\n2     <NA>\nName: A, dtype: boolean"

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 4 Column: 1

              import pandas as pd


def test_repr():
    df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
    expected = "       A\n0   True\n1  False\n2   <NA>"
    assert repr(df) == expected

    expected = "0     True\n1    False\n2     <NA>\nName: A, dtype: boolean"

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 5 Column: 5

              

def test_repr():
    df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
    expected = "       A\n0   True\n1  False\n2   <NA>"
    assert repr(df) == expected

    expected = "0     True\n1    False\n2     <NA>\nName: A, dtype: boolean"
    assert repr(df.A) == expected

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 7
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              def test_repr():
    df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
    expected = "       A\n0   True\n1  False\n2   <NA>"
    assert repr(df) == expected

    expected = "0     True\n1    False\n2     <NA>\nName: A, dtype: boolean"
    assert repr(df.A) == expected

    expected = "<BooleanArray>\n[True, False, <NA>]\nLength: 3, dtype: boolean"

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 10
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  assert repr(df) == expected

    expected = "0     True\n1    False\n2     <NA>\nName: A, dtype: boolean"
    assert repr(df.A) == expected

    expected = "<BooleanArray>\n[True, False, <NA>]\nLength: 3, dtype: boolean"
    assert repr(df.A.array) == expected

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 13
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  assert repr(df.A) == expected

    expected = "<BooleanArray>\n[True, False, <NA>]\nLength: 3, dtype: boolean"
    assert repr(df.A.array) == expected

            

Reported by Bandit.

pandas/tests/arrays/categorical/common.py
6 issues
Unused argument 'method'
Error

Line: 5 Column: 28

              

class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

Attribute 'factor' defined outside __init__
Error

Line: 6 Column: 9

              
class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from pandas import Categorical


class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 4 Column: 1

              from pandas import Categorical


class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

Missing class docstring
Error

Line: 4 Column: 1

              from pandas import Categorical


class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 5 Column: 5

              

class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )

            

Reported by Pylint.

pandas/core/dtypes/base.py
6 issues
No name 'hashtable' in module 'pandas._libs'
Error

Line: 17 Column: 1

              
import numpy as np

from pandas._libs.hashtable import object_hash
from pandas._typing import (
    DtypeObj,
    npt,
    type_t,
)

            

Reported by Pylint.

Unable to import 'pandas._libs.hashtable'
Error

Line: 17 Column: 1

              
import numpy as np

from pandas._libs.hashtable import object_hash
from pandas._typing import (
    DtypeObj,
    npt,
    type_t,
)

            

Reported by Pylint.

Comparing against a callable, did you omit the parenthesis?
Error

Line: 264 Column: 12

                      # error: Non-overlapping equality check (left operand type: "str", right
        #  operand type: "Callable[[ExtensionDtype], str]")  [comparison-overlap]
        assert isinstance(cls.name, str), (cls, type(cls.name))
        if string != cls.name:
            raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'")
        return cls()

    @classmethod
    def is_dtype(cls, dtype: object) -> bool:

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 263
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          )
        # error: Non-overlapping equality check (left operand type: "str", right
        #  operand type: "Callable[[ExtensionDtype], str]")  [comparison-overlap]
        assert isinstance(cls.name, str), (cls, type(cls.name))
        if string != cls.name:
            raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'")
        return cls()

    @classmethod

            

Reported by Bandit.

Unnecessary "elif" after "return"
Error

Line: 294 Column: 9

                      """
        dtype = getattr(dtype, "dtype", dtype)

        if isinstance(dtype, (ABCSeries, ABCIndex, ABCDataFrame, np.dtype)):
            # https://github.com/pandas-dev/pandas/issues/22960
            # avoid passing data to `construct_from_string`. This could
            # cause a FutureWarning from numpy about failing elementwise
            # comparison from, e.g., comparing DataFrame == 'category'.
            return False

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 362 Column: 9

                      -------
        Common dtype (np.dtype or ExtensionDtype) or None
        """
        if len(set(dtypes)) == 1:
            # only itself
            return self
        else:
            return None


            

Reported by Pylint.

pandas/core/computation/engines.py
6 issues
Unable to import 'numexpr'
Error

Line: 113 Column: 9

                  has_neg_frac = True

    def _evaluate(self):
        import numexpr as ne

        # convert the expression to a valid numexpr expression
        s = self.convert()

        env = self.expr.env

            

Reported by Pylint.

Unnecessary pass statement
Error

Line: 104 Column: 9

                      -----
        Must be implemented by subclasses.
        """
        pass


class NumExprEngine(AbstractEngine):
    """NumExpr engine class"""


            

Reported by Pylint.

Missing class docstring
Error

Line: 23 Column: 1

              _ne_builtins = frozenset(MATHOPS + REDUCTIONS)


class NumExprClobberingError(NameError):
    pass


def _check_ne_builtin_clash(expr: Expr) -> None:
    """

            

Reported by Pylint.

Variable name "s" doesn't conform to snake_case naming style
Error

Line: 40 Column: 9

                  overlap = names & _ne_builtins

    if overlap:
        s = ", ".join([repr(x) for x in overlap])
        raise NumExprClobberingError(
            f'Variables in expression "{expr}" overlap with builtins: ({s})'
        )



            

Reported by Pylint.

Import outside toplevel (numexpr)
Error

Line: 113 Column: 9

                  has_neg_frac = True

    def _evaluate(self):
        import numexpr as ne

        # convert the expression to a valid numexpr expression
        s = self.convert()

        env = self.expr.env

            

Reported by Pylint.

Variable name "s" doesn't conform to snake_case naming style
Error

Line: 116 Column: 9

                      import numexpr as ne

        # convert the expression to a valid numexpr expression
        s = self.convert()

        env = self.expr.env
        scope = env.full_scope
        _check_ne_builtin_clash(self.expr)
        return ne.evaluate(s, local_dict=scope)

            

Reported by Pylint.

pandas/tests/arrays/categorical/test_replace.py
6 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

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


@pytest.mark.parametrize(

            

Reported by Pylint.

TODO: better name
Error

Line: 63 Column: 3

                  ],
)
def test_replace2(to_replace, value, result, expected_error_msg):
    # TODO: better name
    # GH#26988
    cat = Categorical(["a", "b"])
    expected = Categorical(result)
    result = cat.replace(to_replace, value)
    tm.assert_categorical_equal(result, expected)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

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


@pytest.mark.parametrize(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

                      # check_categorical sorts categories, which crashes on mixed dtypes
        (3, "4", [1, 2, "4"], False),
        ([1, 2, "3"], "5", ["5", "5", 3], True),
    ],
)
def test_replace(to_replace, value, expected, flip_categories):
    # GH 31720
    stays_categorical = not isinstance(value, list) or len(pd.unique(value)) == 1


            

Reported by Pylint.

Variable name "s" doesn't conform to snake_case naming style
Error

Line: 36 Column: 5

                  # GH 31720
    stays_categorical = not isinstance(value, list) or len(pd.unique(value)) == 1

    s = pd.Series([1, 2, 3], dtype="category")
    result = s.replace(to_replace, value)
    expected = pd.Series(expected, dtype="category")
    s.replace(to_replace, value, inplace=True)

    if flip_categories:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 60 Column: 1

                      # https://github.com/pandas-dev/pandas/issues/33288
        ("a", "a", ["a", "b"], None),
        ("b", None, ["a", None], "Categorical.categories length are different"),
    ],
)
def test_replace2(to_replace, value, result, expected_error_msg):
    # TODO: better name
    # GH#26988
    cat = Categorical(["a", "b"])

            

Reported by Pylint.

pandas/core/arrays/sparse/dtype.py
6 issues
Useless super delegation in method '__hash__'
Error

Line: 102 Column: 5

                      self._dtype = dtype
        self._fill_value = fill_value

    def __hash__(self):
        # Python3 doesn't inherit __hash__ when a base class overrides
        # __eq__, so we explicitly do it here.
        return super().__hash__()

    def __eq__(self, other: Any) -> bool:

            

Reported by Pylint.

TODO for now only handle SparseDtypes and numpy dtypes => extend
Error

Line: 373 Column: 3

                      return self.subtype

    def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
        # TODO for now only handle SparseDtypes and numpy dtypes => extend
        # with other compatibtle extension dtypes
        if any(
            isinstance(x, ExtensionDtype) and not isinstance(x, SparseDtype)
            for x in dtypes
        ):

            

Reported by Pylint.

Consider using ternary (isinstance(self.fill_value, type(other.fill_value)) if other._is_na_fill_value else isinstance(other.fill_value, type(self.fill_value)))
Error

Line: 124 Column: 17

                              # SparseDtype(float, np.nan)     != SparseDtype(float, pd.NaT)
                # i.e. we want to treat any floating-point NaN as equal, but
                # not a floating-point NaN and a datetime NaT.
                fill_value = (
                    other._is_na_fill_value
                    and isinstance(self.fill_value, type(other.fill_value))
                    or isinstance(other.fill_value, type(self.fill_value))
                )
            else:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 175 Column: 5

                      return self.subtype.type

    @property
    def subtype(self):
        return self._dtype

    @property
    def name(self):
        return f"Sparse[{self.subtype.name}, {repr(self.fill_value)}]"

            

Reported by Pylint.

Import outside toplevel (pandas.core.arrays.sparse.array.SparseArray)
Error

Line: 194 Column: 9

                      -------
        type
        """
        from pandas.core.arrays.sparse.array import SparseArray

        return SparseArray

    @classmethod
    def construct_from_string(cls, string: str) -> SparseDtype:

            

Reported by Pylint.

Variable name "m" doesn't conform to snake_case naming style
Error

Line: 273 Column: 9

                          When the subtype cannot be extracted.
        """
        xpr = re.compile(r"Sparse\[(?P<subtype>[^,]*)(, )?(?P<fill_value>.*?)?\]$")
        m = xpr.match(dtype)
        has_fill_value = False
        if m:
            subtype = m.groupdict()["subtype"]
            has_fill_value = bool(m.groupdict()["fill_value"])
        elif dtype == "Sparse":

            

Reported by Pylint.