The following issues were found

pandas/tests/util/test_assert_produces_warning.py
31 issues
Unable to import 'pytest'
Error

Line: 6 Column: 1

              """
import warnings

import pytest

from pandas.errors import (
    DtypeWarning,
    PerformanceWarning,
)

            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 92 Column: 43

                      ("Message, which we do not match", None),
    ],
)
def test_catch_warning_category_and_match(category, message, match):
    with tm.assert_produces_warning(category, match=match):
        warnings.warn(message, category)


def test_fail_to_match_runtime_warning():

            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 98 Column: 5

              

def test_fail_to_match_runtime_warning():
    category = RuntimeWarning
    match = "Did not see this warning"
    unmatched = (
        r"Did not see warning 'RuntimeWarning' matching 'Did not see this warning'. "
        r"The emitted warning messages are "
        r"\[RuntimeWarning\('This is not a match.'\), "

            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 113 Column: 5

              

def test_fail_to_match_future_warning():
    category = FutureWarning
    match = "Warning"
    unmatched = (
        r"Did not see warning 'FutureWarning' matching 'Warning'. "
        r"The emitted warning messages are "
        r"\[FutureWarning\('This is not a match.'\), "

            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 128 Column: 5

              

def test_fail_to_match_resource_warning():
    category = ResourceWarning
    match = r"\d+"
    unmatched = (
        r"Did not see warning 'ResourceWarning' matching '\\d\+'. "
        r"The emitted warning messages are "
        r"\[ResourceWarning\('This is not a match.'\), "

            

Reported by Pylint.

Redefining name 'pair_different_warnings' from outer scope (line 48)
Error

Line: 142 Column: 39

                          warnings.warn("Another unmatched warning.", category)


def test_fail_to_catch_actual_warning(pair_different_warnings):
    expected_category, actual_category = pair_different_warnings
    match = "Did not see expected warning of class"
    with pytest.raises(AssertionError, match=match):
        with tm.assert_produces_warning(expected_category):
            warnings.warn("warning message", actual_category)

            

Reported by Pylint.

Redefining name 'pair_different_warnings' from outer scope (line 48)
Error

Line: 150 Column: 31

                          warnings.warn("warning message", actual_category)


def test_ignore_extra_warning(pair_different_warnings):
    expected_category, extra_category = pair_different_warnings
    with tm.assert_produces_warning(expected_category, raise_on_extra_warnings=False):
        warnings.warn("Expected warning", expected_category)
        warnings.warn("Unexpected warning OK", extra_category)


            

Reported by Pylint.

Redefining name 'pair_different_warnings' from outer scope (line 48)
Error

Line: 157 Column: 33

                      warnings.warn("Unexpected warning OK", extra_category)


def test_raise_on_extra_warning(pair_different_warnings):
    expected_category, extra_category = pair_different_warnings
    match = r"Caused unexpected warning\(s\)"
    with pytest.raises(AssertionError, match=match):
        with tm.assert_produces_warning(expected_category):
            warnings.warn("Expected warning", expected_category)

            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 167 Column: 5

              

def test_same_category_different_messages_first_match():
    category = UserWarning
    with tm.assert_produces_warning(category, match=r"^Match this"):
        warnings.warn("Match this", category)
        warnings.warn("Do not match that", category)
        warnings.warn("Do not match that either", category)


            

Reported by Pylint.

Redefining name 'category' from outer scope (line 25)
Error

Line: 175 Column: 5

              

def test_same_category_different_messages_last_match():
    category = DeprecationWarning
    with tm.assert_produces_warning(category, match=r"^Match this"):
        warnings.warn("Do not match that", category)
        warnings.warn("Do not match that either", category)
        warnings.warn("Match this", category)


            

Reported by Pylint.

pandas/tests/io/excel/test_xlwt.py
31 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import re

import numpy as np
import pytest

from pandas import (
    DataFrame,
    MultiIndex,
    options,

            

Reported by Pylint.

Abstract class 'ExcelWriter' with abstract methods instantiated
Error

Line: 80 Column: 13

              
    with tm.ensure_clean(ext) as f:
        with pytest.raises(ValueError, match=msg):
            ExcelWriter(f, engine="xlwt", mode="a")


def test_to_excel_xlwt_warning(ext):
    # GH 26552
    df = DataFrame(np.random.randn(3, 10))

            

Reported by Pylint.

Abstract class 'ExcelWriter' with abstract methods instantiated
Error

Line: 112 Column: 18

                  with tm.ensure_clean(ext) as f:
        msg = re.escape("Use of **kwargs is deprecated")
        with tm.assert_produces_warning(FutureWarning, match=msg):
            with ExcelWriter(f, engine="openpyxl", **kwargs) as writer:
                # xlwt won't allow us to close without writing something
                DataFrame().to_excel(writer)


@pytest.mark.parametrize("write_only", [True, False])

            

Reported by Pylint.

Abstract class 'ExcelWriter' with abstract methods instantiated
Error

Line: 123 Column: 14

                  # xlwt doesn't utilize kwargs, only test that supplying a engine_kwarg works
    engine_kwargs = {"write_only": write_only}
    with tm.ensure_clean(ext) as f:
        with ExcelWriter(f, engine="openpyxl", engine_kwargs=engine_kwargs) as writer:
            # xlwt won't allow us to close without writing something
            DataFrame().to_excel(writer)

            

Reported by Pylint.

Unused argument 'ext'
Error

Line: 58 Column: 34

                      df.to_excel(path, index=False)


def test_to_excel_styleconverter(ext):
    hstyle = {
        "font": {"bold": True},
        "borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"},
        "alignment": {"horizontal": "center", "vertical": "top"},
    }

            

Reported by Pylint.

Access to a protected member _convert_to_style of a client class
Error

Line: 65 Column: 17

                      "alignment": {"horizontal": "center", "vertical": "top"},
    }

    xls_style = _XlwtWriter._convert_to_style(hstyle)
    assert xls_style.font.bold
    assert xlwt.Borders.THIN == xls_style.borders.top
    assert xlwt.Borders.THIN == xls_style.borders.right
    assert xlwt.Borders.THIN == xls_style.borders.bottom
    assert xlwt.Borders.THIN == xls_style.borders.left

            

Reported by Pylint.

Unused argument 'ext'
Error

Line: 94 Column: 39

                          df.to_excel(path)


def test_option_xls_writer_deprecated(ext):
    # GH 26552
    with tm.assert_produces_warning(
        FutureWarning,
        match="As the xlwt package is no longer maintained",
        check_stacklevel=False,

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import re

import numpy as np
import pytest

from pandas import (
    DataFrame,
    MultiIndex,
    options,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

              pytestmark = pytest.mark.parametrize("ext,", [".xls"])


def test_excel_raise_error_on_multiindex_columns_and_no_index(ext):
    # MultiIndex as columns is not yet implemented 9794
    cols = MultiIndex.from_tuples(
        [("site", ""), ("2014", "height"), ("2014", "weight")]
    )
    df = DataFrame(np.random.randn(10, 3), columns=cols)

            

Reported by Pylint.

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

Line: 28 Column: 5

                  cols = MultiIndex.from_tuples(
        [("site", ""), ("2014", "height"), ("2014", "weight")]
    )
    df = DataFrame(np.random.randn(10, 3), columns=cols)

    msg = (
        "Writing to Excel with MultiIndex columns and no index "
        "\\('index'=False\\) is not yet implemented."
    )

            

Reported by Pylint.

pandas/tests/indexes/multi/test_drop.py
31 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import warnings

import numpy as np
import pytest

from pandas.errors import PerformanceWarning

import pandas as pd
from pandas import (

            

Reported by Pylint.

Instance of 'tuple' has no 'droplevel' member
Error

Line: 107 Column: 15

                      names=["one", "two", "three"],
    )

    dropped = index[:2].droplevel(["three", "one"])
    expected = index[:2].droplevel(2).droplevel(0)
    assert dropped.equals(expected)

    dropped = index[:2].droplevel([])
    expected = index[:2]

            

Reported by Pylint.

Instance of 'tuple' has no 'droplevel' member
Error

Line: 108 Column: 16

                  )

    dropped = index[:2].droplevel(["three", "one"])
    expected = index[:2].droplevel(2).droplevel(0)
    assert dropped.equals(expected)

    dropped = index[:2].droplevel([])
    expected = index[:2]
    assert dropped.equals(expected)

            

Reported by Pylint.

Instance of 'tuple' has no 'droplevel' member
Error

Line: 111 Column: 15

                  expected = index[:2].droplevel(2).droplevel(0)
    assert dropped.equals(expected)

    dropped = index[:2].droplevel([])
    expected = index[:2]
    assert dropped.equals(expected)

    msg = (
        "Cannot remove 3 levels from an index with 3 levels: "

            

Reported by Pylint.

Instance of 'tuple' has no 'droplevel' member
Error

Line: 120 Column: 9

                      "at least one level must be left"
    )
    with pytest.raises(ValueError, match=msg):
        index[:2].droplevel(["one", "two", "three"])

    with pytest.raises(KeyError, match="'Level four not found'"):
        index[:2].droplevel(["one", "four"])



            

Reported by Pylint.

Instance of 'tuple' has no 'droplevel' member
Error

Line: 123 Column: 9

                      index[:2].droplevel(["one", "two", "three"])

    with pytest.raises(KeyError, match="'Level four not found'"):
        index[:2].droplevel(["one", "four"])


def test_drop_not_lexsorted():
    # GH 12078


            

Reported by Pylint.

Access to a protected member _is_lexsorted of a client class
Error

Line: 132 Column: 12

                  # define the lexsorted version of the multi-index
    tuples = [("a", ""), ("b1", "c1"), ("b2", "c2")]
    lexsorted_mi = MultiIndex.from_tuples(tuples, names=["b", "c"])
    assert lexsorted_mi._is_lexsorted()

    # and the not-lexsorted version
    df = pd.DataFrame(
        columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
    )

            

Reported by Pylint.

Access to a protected member _is_lexsorted of a client class
Error

Line: 141 Column: 16

                  df = df.pivot_table(index="a", columns=["b", "c"], values="d")
    df = df.reset_index()
    not_lexsorted_mi = df.columns
    assert not not_lexsorted_mi._is_lexsorted()

    # compare the results
    tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi)
    with tm.assert_produces_warning(PerformanceWarning):
        tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a"))

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import warnings

import numpy as np
import pytest

from pandas.errors import PerformanceWarning

import pandas as pd
from pandas import (

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 1

              import pandas._testing as tm


def test_drop(idx):
    dropped = idx.drop([("foo", "two"), ("qux", "one")])

    index = MultiIndex.from_tuples([("foo", "two"), ("qux", "one")])
    dropped2 = idx.drop(index)


            

Reported by Pylint.

pandas/tests/window/moments/test_moments_rolling_skew_kurt.py
31 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              from functools import partial

import numpy as np
import pytest

import pandas.util._test_decorators as td

from pandas import (
    DataFrame,

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 23 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_series(series, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    result = getattr(series.rolling(50), roll_func)()
    assert isinstance(result, Series)
    tm.assert_almost_equal(result.iloc[-1], compare_func(series[-50:]))

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 34 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_frame(raw, frame, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    result = getattr(frame.rolling(50), roll_func)()
    assert isinstance(result, DataFrame)
    tm.assert_series_equal(

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 49 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_time_rule_series(series, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    win = 25
    ser = series[::2].resample("B").mean()
    series_result = getattr(ser.rolling(window=win, min_periods=10), roll_func)()

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 65 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_time_rule_frame(raw, frame, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    win = 25
    frm = frame[::2].resample("B").mean()
    frame_result = getattr(frm.rolling(window=win, min_periods=10), roll_func)()

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 85 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_nans(sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    obj = Series(np.random.randn(50))
    obj[:10] = np.NaN
    obj[-10:] = np.NaN

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from functools import partial

import numpy as np
import pytest

import pandas.util._test_decorators as td

from pandas import (
    DataFrame,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 1

              
@td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_series(series, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    result = getattr(series.rolling(50), roll_func)()
    assert isinstance(result, Series)

            

Reported by Pylint.

Import outside toplevel (scipy.stats)
Error

Line: 23 Column: 5

              @td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])
def test_series(series, sp_func, roll_func):
    import scipy.stats

    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    result = getattr(series.rolling(50), roll_func)()
    assert isinstance(result, Series)
    tm.assert_almost_equal(result.iloc[-1], compare_func(series[-50:]))

            

Reported by Pylint.

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

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

              
    compare_func = partial(getattr(scipy.stats, sp_func), bias=False)
    result = getattr(series.rolling(50), roll_func)()
    assert isinstance(result, Series)
    tm.assert_almost_equal(result.iloc[-1], compare_func(series[-50:]))


@td.skip_if_no_scipy
@pytest.mark.parametrize("sp_func, roll_func", [["kurtosis", "kurt"], ["skew", "skew"]])

            

Reported by Bandit.

pandas/tests/apply/test_str.py
31 issues
Unable to import 'pytest'
Error

Line: 5 Column: 1

              import operator

import numpy as np
import pytest

from pandas.core.dtypes.common import is_number

from pandas import (
    DataFrame,

            

Reported by Pylint.

TODO(ArrayManager) shift with axis=1
Error

Line: 253 Column: 3

              ):
    # GH 35964
    if using_array_manager and op == "pct_change" and axis in (1, "columns"):
        # TODO(ArrayManager) shift with axis=1
        request.node.add_marker(
            pytest.mark.xfail(
                reason="shift axis=1 not yet implemented for ArrayManager"
            )
        )

            

Reported by Pylint.

Access to a protected member _mgr of a client class
Error

Line: 272 Column: 16

                  # same thing, but ensuring we have multiple blocks
    assert "E" not in float_frame.columns
    float_frame["E"] = float_frame["A"].copy()
    assert len(float_frame._mgr.arrays) > 1

    if axis == 0 or axis == "index":
        ones = np.ones(float_frame.shape[0])
    else:
        ones = np.ones(float_frame.shape[1])

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from itertools import chain
import operator

import numpy as np
import pytest

from pandas.core.dtypes.common import is_number

from pandas import (

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 1

                      pytest.param([], {"numeric_only": True}, id="optional_kwds"),
        pytest.param([1, None], {"numeric_only": True}, id="args_and_kwds"),
    ],
)
@pytest.mark.parametrize("how", ["agg", "apply"])
def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how):
    if len(args) > 1 and how == "agg":
        request.node.add_marker(
            pytest.mark.xfail(

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 31 Column: 1

                      pytest.param([], {"numeric_only": True}, id="optional_kwds"),
        pytest.param([1, None], {"numeric_only": True}, id="args_and_kwds"),
    ],
)
@pytest.mark.parametrize("how", ["agg", "apply"])
def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how):
    if len(args) > 1 and how == "agg":
        request.node.add_marker(
            pytest.mark.xfail(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 47 Column: 1

                  tm.assert_series_equal(result, expected)


def test_with_string_args(datetime_series):

    for arg in ["sum", "mean", "min", "max", "std"]:
        result = datetime_series.apply(arg)
        expected = getattr(datetime_series, arg)()
        assert result == expected

            

Reported by Pylint.

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

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

                  for arg in ["sum", "mean", "min", "max", "std"]:
        result = datetime_series.apply(arg)
        expected = getattr(datetime_series, arg)()
        assert result == expected


@pytest.mark.parametrize("op", ["mean", "median", "std", "var"])
@pytest.mark.parametrize("how", ["agg", "apply"])
def test_apply_np_reducer(float_frame, op, how):

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 57 Column: 1

              
@pytest.mark.parametrize("op", ["mean", "median", "std", "var"])
@pytest.mark.parametrize("how", ["agg", "apply"])
def test_apply_np_reducer(float_frame, op, how):
    # GH 39116
    float_frame = DataFrame({"a": [1, 2], "b": [3, 4]})
    result = getattr(float_frame, how)(op)
    # pandas ddof defaults to 1, numpy to 0
    kwargs = {"ddof": 1} if op in ("std", "var") else {}

            

Reported by Pylint.

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

Line: 57 Column: 1

              
@pytest.mark.parametrize("op", ["mean", "median", "std", "var"])
@pytest.mark.parametrize("how", ["agg", "apply"])
def test_apply_np_reducer(float_frame, op, how):
    # GH 39116
    float_frame = DataFrame({"a": [1, 2], "b": [3, 4]})
    result = getattr(float_frame, how)(op)
    # pandas ddof defaults to 1, numpy to 0
    kwargs = {"ddof": 1} if op in ("std", "var") else {}

            

Reported by Pylint.

pandas/plotting/_matplotlib/timeseries.py
31 issues
Unable to import 'pandas._libs.tslibs.dtypes'
Error

Line: 18 Column: 1

                  Period,
    to_offset,
)
from pandas._libs.tslibs.dtypes import FreqGroup

from pandas.core.dtypes.generic import (
    ABCDatetimeIndex,
    ABCPeriodIndex,
    ABCTimedeltaIndex,

            

Reported by Pylint.

TODO: Use the fact that axis can have units to simplify the process
Error

Line: 1 Column: 3

              # TODO: Use the fact that axis can have units to simplify the process

from __future__ import annotations

import functools
from typing import (
    TYPE_CHECKING,
    cast,
)

            

Reported by Pylint.

Access to a protected member _plot_data of a client class
Error

Line: 122 Column: 5

                  data = getattr(ax, "_plot_data", None)

    # clear current axes and data
    ax._plot_data = []
    ax.clear()

    decorate_axes(ax, freq, kwargs)

    lines = []

            

Reported by Pylint.

Access to a protected member _plot_data of a client class
Error

Line: 134 Column: 13

                          series = series.copy()
            idx = series.index.asfreq(freq, how="S")
            series.index = idx
            ax._plot_data.append((series, plotf, kwds))

            # for tsplot
            if isinstance(plotf, str):
                from pandas.plotting._matplotlib import PLOT_CLASSES


            

Reported by Pylint.

Access to a protected member _plot of a client class
Error

Line: 140 Column: 25

                          if isinstance(plotf, str):
                from pandas.plotting._matplotlib import PLOT_CLASSES

                plotf = PLOT_CLASSES[plotf]._plot

            lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0])
            labels.append(pprint_thing(series.name))

    return lines, labels

            

Reported by Pylint.

Access to a protected member _mpl_repr of a client class
Error

Line: 142 Column: 36

              
                plotf = PLOT_CLASSES[plotf]._plot

            lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0])
            labels.append(pprint_thing(series.name))

    return lines, labels



            

Reported by Pylint.

Access to a protected member _plot_data of a client class
Error

Line: 151 Column: 9

              def decorate_axes(ax: Axes, freq, kwargs):
    """Initialize axes for time-series plotting"""
    if not hasattr(ax, "_plot_data"):
        ax._plot_data = []

    ax.freq = freq
    xaxis = ax.get_xaxis()
    xaxis.freq = freq
    if not hasattr(ax, "legendlabels"):

            

Reported by Pylint.

FIXME: hack this for 0.10.1, creating more technical debt...sigh
Error

Line: 231 Column: 3

                  if freq is None:
        return False

    # FIXME: hack this for 0.10.1, creating more technical debt...sigh
    if isinstance(data.index, ABCDatetimeIndex):
        base = to_offset(freq)._period_dtype_code
        x = data.index
        if base <= FreqGroup.FR_DAY.value:
            return x[:1].is_normalized

            

Reported by Pylint.

Access to a protected member _period_dtype_code of a client class
Error

Line: 233 Column: 16

              
    # FIXME: hack this for 0.10.1, creating more technical debt...sigh
    if isinstance(data.index, ABCDatetimeIndex):
        base = to_offset(freq)._period_dtype_code
        x = data.index
        if base <= FreqGroup.FR_DAY.value:
            return x[:1].is_normalized
        return Period(x[0], freq).to_timestamp().tz_localize(x.tz) == x[0]
    return True

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # TODO: Use the fact that axis can have units to simplify the process

from __future__ import annotations

import functools
from typing import (
    TYPE_CHECKING,
    cast,
)

            

Reported by Pylint.

pandas/tests/frame/test_unary.py
31 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              from decimal import Decimal

import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm



            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 55 Column: 13

                          r"Unary negative expects numeric dtype, not datetime64\[ns\]"
        )
        with pytest.raises(TypeError, match=msg):
            (-df)
        with pytest.raises(TypeError, match=msg):
            (-df["a"])

    def test_invert(self, float_frame):
        df = float_frame

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 57 Column: 13

                      with pytest.raises(TypeError, match=msg):
            (-df)
        with pytest.raises(TypeError, match=msg):
            (-df["a"])

    def test_invert(self, float_frame):
        df = float_frame

        tm.assert_frame_equal(-(df < 0), ~(df < 0))

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 121 Column: 13

                  def test_pos_raises(self, df):
        msg = "Unary plus expects .* dtype, not datetime64\\[ns\\]"
        with pytest.raises(TypeError, match=msg):
            (+df)
        with pytest.raises(TypeError, match=msg):
            (+df["a"])

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 123 Column: 13

                      with pytest.raises(TypeError, match=msg):
            (+df)
        with pytest.raises(TypeError, match=msg):
            (+df["a"])

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from decimal import Decimal

import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm



            

Reported by Pylint.

Missing class docstring
Error

Line: 10 Column: 1

              import pandas._testing as tm


class TestDataFrameUnaryOperators:
    # __pos__, __neg__, __inv__

    @pytest.mark.parametrize(
        "df,expected",
        [

            

Reported by Pylint.

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

Line: 21 Column: 5

                          (
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([1, -1]))}),
            ),
        ],
    )
    def test_neg_numeric(self, df, expected):
        tm.assert_frame_equal(-df, expected)
        tm.assert_series_equal(-df["a"], expected["a"])

            

Reported by Pylint.

Method could be a function
Error

Line: 21 Column: 5

                          (
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([1, -1]))}),
            ),
        ],
    )
    def test_neg_numeric(self, df, expected):
        tm.assert_frame_equal(-df, expected)
        tm.assert_series_equal(-df["a"], expected["a"])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 5

                          (
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([-1, 1]))}),
                pd.DataFrame({"a": pd.Series(pd.to_timedelta([1, -1]))}),
            ),
        ],
    )
    def test_neg_numeric(self, df, expected):
        tm.assert_frame_equal(-df, expected)
        tm.assert_series_equal(-df["a"], expected["a"])

            

Reported by Pylint.

pandas/tests/series/methods/test_explode.py
31 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm


def test_basic():
    s = pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd"), name="foo")

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm


def test_basic():
    s = pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd"), name="foo")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              import pandas._testing as tm


def test_basic():
    s = pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd"), name="foo")
    result = s.explode()
    expected = pd.Series(
        [0, 1, 2, np.nan, np.nan, 3, 4], index=list("aaabcdd"), dtype=object, name="foo"
    )

            

Reported by Pylint.

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

Line: 9 Column: 5

              

def test_basic():
    s = pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd"), name="foo")
    result = s.explode()
    expected = pd.Series(
        [0, 1, 2, np.nan, np.nan, 3, 4], index=list("aaabcdd"), dtype=object, name="foo"
    )
    tm.assert_series_equal(result, expected)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 17 Column: 1

                  tm.assert_series_equal(result, expected)


def test_mixed_type():
    s = pd.Series(
        [[0, 1, 2], np.nan, None, np.array([]), pd.Series(["a", "b"])], name="foo"
    )
    result = s.explode()
    expected = pd.Series(

            

Reported by Pylint.

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

Line: 18 Column: 5

              

def test_mixed_type():
    s = pd.Series(
        [[0, 1, 2], np.nan, None, np.array([]), pd.Series(["a", "b"])], name="foo"
    )
    result = s.explode()
    expected = pd.Series(
        [0, 1, 2, np.nan, None, np.nan, "a", "b"],

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 1

                  tm.assert_series_equal(result, expected)


def test_empty():
    s = pd.Series(dtype=object)
    result = s.explode()
    expected = s.copy()
    tm.assert_series_equal(result, expected)


            

Reported by Pylint.

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

Line: 32 Column: 5

              

def test_empty():
    s = pd.Series(dtype=object)
    result = s.explode()
    expected = s.copy()
    tm.assert_series_equal(result, expected)



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 38 Column: 1

                  tm.assert_series_equal(result, expected)


def test_nested_lists():
    s = pd.Series([[[1, 2, 3]], [1, 2], 1])
    result = s.explode()
    expected = pd.Series([[1, 2, 3], 1, 2, 1], index=[0, 1, 1, 2])
    tm.assert_series_equal(result, expected)


            

Reported by Pylint.

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

Line: 39 Column: 5

              

def test_nested_lists():
    s = pd.Series([[[1, 2, 3]], [1, 2], 1])
    result = s.explode()
    expected = pd.Series([[1, 2, 3], 1, 2, 1], index=[0, 1, 1, 2])
    tm.assert_series_equal(result, expected)



            

Reported by Pylint.

pandas/tests/indexes/ranges/test_join.py
31 issues
Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

from pandas import (
    Index,
    Int64Index,
    RangeIndex,
)
import pandas._testing as tm


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              import pandas._testing as tm


class TestJoin:
    def test_join_outer(self):
        # join with Int64Index
        index = RangeIndex(start=0, stop=20, step=2)
        other = Int64Index(np.arange(25, 14, -1))


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 5

              

class TestJoin:
    def test_join_outer(self):
        # join with Int64Index
        index = RangeIndex(start=0, stop=20, step=2)
        other = Int64Index(np.arange(25, 14, -1))

        res, lidx, ridx = index.join(other, how="outer", return_indexers=True)

            

Reported by Pylint.

Method could be a function
Error

Line: 12 Column: 5

              

class TestJoin:
    def test_join_outer(self):
        # join with Int64Index
        index = RangeIndex(start=0, stop=20, step=2)
        other = Int64Index(np.arange(25, 14, -1))

        res, lidx, ridx = index.join(other, how="outer", return_indexers=True)

            

Reported by Pylint.

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

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

                          dtype=np.intp,
        )

        assert isinstance(res, Int64Index)
        assert not isinstance(res, RangeIndex)
        tm.assert_index_equal(res, eres)
        tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)


            

Reported by Bandit.

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

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

                      )

        assert isinstance(res, Int64Index)
        assert not isinstance(res, RangeIndex)
        tm.assert_index_equal(res, eres)
        tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)

        # join with RangeIndex

            

Reported by Bandit.

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

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

                      noidx_res = index.join(other, how="outer")
        tm.assert_index_equal(res, noidx_res)

        assert isinstance(res, Int64Index)
        assert not isinstance(res, RangeIndex)
        tm.assert_index_equal(res, eres)
        tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)


            

Reported by Bandit.

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

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

                      tm.assert_index_equal(res, noidx_res)

        assert isinstance(res, Int64Index)
        assert not isinstance(res, RangeIndex)
        tm.assert_index_equal(res, eres)
        tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)

    def test_join_inner(self):

            

Reported by Bandit.

Method could be a function
Error

Line: 52 Column: 5

                      tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)

    def test_join_inner(self):
        # Join with non-RangeIndex
        index = RangeIndex(start=0, stop=20, step=2)
        other = Int64Index(np.arange(25, 14, -1))

        res, lidx, ridx = index.join(other, how="inner", return_indexers=True)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 52 Column: 5

                      tm.assert_numpy_array_equal(lidx, elidx)
        tm.assert_numpy_array_equal(ridx, eridx)

    def test_join_inner(self):
        # Join with non-RangeIndex
        index = RangeIndex(start=0, stop=20, step=2)
        other = Int64Index(np.arange(25, 14, -1))

        res, lidx, ridx = index.join(other, how="inner", return_indexers=True)

            

Reported by Pylint.

pandas/util/_doctools.py
31 issues
Redefining name 'col' from outer scope (line 189)
Error

Line: 28 Column: 14

                      """
        Calculate table shape considering index levels.
        """
        row, col = df.shape
        return row + df.columns.nlevels, col + df.index.nlevels

    def _get_cells(self, left, right, vertical) -> tuple[int, int]:
        """
        Calculate appropriate figure size based on left and right data.

            

Reported by Pylint.

Redefining name 'plt' from outer scope (line 169)
Error

Line: 57 Column: 9

                          If True, use vertical layout. If False, use horizontal layout.
        """
        import matplotlib.gridspec as gridspec
        import matplotlib.pyplot as plt

        if not isinstance(left, list):
            left = [left]
        left = [self._conv(df) for df in left]
        right = self._conv(right)

            

Reported by Pylint.

Access to a protected member _get_level_values of a client class
Error

Line: 123 Column: 45

                          data.insert(0, "Index", data.index)
        else:
            for i in range(idx_nlevels):
                data.insert(i, f"Index{i}", data.index._get_level_values(i))

        col_nlevels = data.columns.nlevels
        if col_nlevels > 1:
            col = data.columns._get_level_values(0)
            values = [

            

Reported by Pylint.

Access to a protected member _get_level_values of a client class
Error

Line: 127 Column: 19

              
        col_nlevels = data.columns.nlevels
        if col_nlevels > 1:
            col = data.columns._get_level_values(0)
            values = [
                data.columns._get_level_values(i)._values for i in range(1, col_nlevels)
            ]
            col_df = pd.DataFrame(values)
            data.columns = col_df.columns

            

Reported by Pylint.

Redefining name 'col' from outer scope (line 189)
Error

Line: 127 Column: 13

              
        col_nlevels = data.columns.nlevels
        if col_nlevels > 1:
            col = data.columns._get_level_values(0)
            values = [
                data.columns._get_level_values(i)._values for i in range(1, col_nlevels)
            ]
            col_df = pd.DataFrame(values)
            data.columns = col_df.columns

            

Reported by Pylint.

Access to a protected member _get_level_values of a client class
Error

Line: 129 Column: 17

                      if col_nlevels > 1:
            col = data.columns._get_level_values(0)
            values = [
                data.columns._get_level_values(i)._values for i in range(1, col_nlevels)
            ]
            col_df = pd.DataFrame(values)
            data.columns = col_df.columns
            data = pd.concat([col_df, data])
            data.columns = col

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 129 Column: 17

                      if col_nlevels > 1:
            col = data.columns._get_level_values(0)
            values = [
                data.columns._get_level_values(i)._values for i in range(1, col_nlevels)
            ]
            col_df = pd.DataFrame(values)
            data.columns = col_df.columns
            data = pd.concat([col_df, data])
            data.columns = col

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import annotations

import numpy as np

import pandas as pd


class TablePlotter:
    """

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 8 Column: 1

              import pandas as pd


class TablePlotter:
    """
    Layout some DataFrames in vertical/horizontal layout for explanation.
    Used in merging.rst
    """


            

Reported by Pylint.

Method could be a function
Error

Line: 24 Column: 5

                      self.cell_height = cell_height
        self.font_size = font_size

    def _shape(self, df: pd.DataFrame) -> tuple[int, int]:
        """
        Calculate table shape considering index levels.
        """
        row, col = df.shape
        return row + df.columns.nlevels, col + df.index.nlevels

            

Reported by Pylint.