The following issues were found
pandas/tests/dtypes/cast/test_construct_ndarray.py
5 issues
Line: 2
Column: 1
import numpy as np
import pytest
import pandas._testing as tm
from pandas.core.construction import sanitize_array
@pytest.mark.parametrize(
"values, dtype, expected",
Reported by Pylint.
Line: 1
Column: 1
import numpy as np
import pytest
import pandas._testing as tm
from pandas.core.construction import sanitize_array
@pytest.mark.parametrize(
"values, dtype, expected",
Reported by Pylint.
Line: 16
Column: 1
(["1", "2", None], None, np.array(["1", "2", None])),
(["1", "2", None], np.dtype("str"), np.array(["1", "2", None])),
([1, 2, None], np.dtype("str"), np.array(["1", "2", None])),
],
)
def test_construct_1d_ndarray_preserving_na(values, dtype, expected):
result = sanitize_array(values, index=None, dtype=dtype)
tm.assert_numpy_array_equal(result, expected)
Reported by Pylint.
Line: 24
Column: 1
@pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"])
def test_construct_1d_ndarray_preserving_na_datetimelike(dtype):
arr = np.arange(5, dtype=np.int64).view(dtype)
expected = np.array(list(arr), dtype=object)
assert all(isinstance(x, type(arr[0])) for x in expected)
result = sanitize_array(arr, index=None, dtype=np.dtype(object))
Reported by Pylint.
Line: 27
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_construct_1d_ndarray_preserving_na_datetimelike(dtype):
arr = np.arange(5, dtype=np.int64).view(dtype)
expected = np.array(list(arr), dtype=object)
assert all(isinstance(x, type(arr[0])) for x in expected)
result = sanitize_array(arr, index=None, dtype=np.dtype(object))
tm.assert_numpy_array_equal(result, expected)
Reported by Bandit.
pandas/core/util/numba_.py
5 issues
Line: 24
Column: 5
def set_use_numba(enable: bool = False) -> None:
global GLOBAL_USE_NUMBA
if enable:
import_optional_dependency("numba")
GLOBAL_USE_NUMBA = enable
Reported by Pylint.
Line: 101
Column: 24
else:
@numba.generated_jit(nopython=nopython, nogil=nogil, parallel=parallel)
def numba_func(data, *_args):
if getattr(np, func.__name__, False) is func or isinstance(
func, types.BuiltinFunctionType
):
jf = func
else:
Reported by Pylint.
Line: 23
Column: 1
return engine == "numba" or (engine is None and GLOBAL_USE_NUMBA)
def set_use_numba(enable: bool = False) -> None:
global GLOBAL_USE_NUMBA
if enable:
import_optional_dependency("numba")
GLOBAL_USE_NUMBA = enable
Reported by Pylint.
Line: 105
Column: 17
if getattr(np, func.__name__, False) is func or isinstance(
func, types.BuiltinFunctionType
):
jf = func
else:
jf = numba.jit(func, nopython=nopython, nogil=nogil)
def impl(data, *_args):
return jf(data, *_args)
Reported by Pylint.
Line: 107
Column: 17
):
jf = func
else:
jf = numba.jit(func, nopython=nopython, nogil=nogil)
def impl(data, *_args):
return jf(data, *_args)
return impl
Reported by Pylint.
pandas/tests/arrays/boolean/test_astype.py
5 issues
Line: 2
Column: 1
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_astype():
# with missing values
Reported by Pylint.
Line: 1
Column: 1
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_astype():
# with missing values
Reported by Pylint.
Line: 8
Column: 1
import pandas._testing as tm
def test_astype():
# with missing values
arr = pd.array([True, False, None], dtype="boolean")
with pytest.raises(ValueError, match="cannot convert NA to integer"):
arr.astype("int64")
Reported by Pylint.
Line: 37
Column: 1
tm.assert_numpy_array_equal(result, expected)
def test_astype_to_boolean_array():
# astype to BooleanArray
arr = pd.array([True, False, None], dtype="boolean")
result = arr.astype("boolean")
tm.assert_extension_array_equal(result, arr)
Reported by Pylint.
Line: 47
Column: 1
tm.assert_extension_array_equal(result, arr)
def test_astype_to_integer_array():
# astype to IntegerArray
arr = pd.array([True, False, None], dtype="boolean")
result = arr.astype("Int64")
expected = pd.array([1, 0, None], dtype="Int64")
Reported by Pylint.
pandas/tests/frame/methods/test_head_tail.py
5 issues
Line: 1
Column: 1
import numpy as np
from pandas import DataFrame
import pandas._testing as tm
def test_head_tail_generic(index, frame_or_series):
# GH#5370
Reported by Pylint.
Line: 7
Column: 1
import pandas._testing as tm
def test_head_tail_generic(index, frame_or_series):
# GH#5370
ndim = 2 if frame_or_series is DataFrame else 1
shape = (len(index),) * ndim
vals = np.random.randn(*shape)
Reported by Pylint.
Line: 31
Column: 1
tm.assert_equal(obj.tail(-3), obj.tail(len(index) - 3))
def test_head_tail(float_frame):
tm.assert_frame_equal(float_frame.head(), float_frame[:5])
tm.assert_frame_equal(float_frame.tail(), float_frame[-5:])
tm.assert_frame_equal(float_frame.head(0), float_frame[0:0])
tm.assert_frame_equal(float_frame.tail(0), float_frame[0:0])
Reported by Pylint.
Line: 43
Column: 5
tm.assert_frame_equal(float_frame.head(1), float_frame[:1])
tm.assert_frame_equal(float_frame.tail(1), float_frame[-1:])
# with a float index
df = float_frame.copy()
df.index = np.arange(len(float_frame)) + 0.1
tm.assert_frame_equal(df.head(), df.iloc[:5])
tm.assert_frame_equal(df.tail(), df.iloc[-5:])
tm.assert_frame_equal(df.head(0), df[0:0])
tm.assert_frame_equal(df.tail(0), df[0:0])
Reported by Pylint.
Line: 53
Column: 1
tm.assert_frame_equal(df.tail(-1), df.iloc[1:])
def test_head_tail_empty():
# test empty dataframe
empty_df = DataFrame()
tm.assert_frame_equal(empty_df.tail(), empty_df)
tm.assert_frame_equal(empty_df.head(), empty_df)
Reported by Pylint.
pandas/tests/api/test_types.py
5 issues
Line: 1
Column: 1
import pandas._testing as tm
from pandas.api import types
from pandas.tests.api.test_api import Base
class TestTypes(Base):
allowed = [
"is_bool",
Reported by Pylint.
Line: 6
Column: 1
from pandas.tests.api.test_api import Base
class TestTypes(Base):
allowed = [
"is_bool",
"is_bool_dtype",
"is_categorical",
Reported by Pylint.
Line: 55
Column: 5
deprecated = ["is_extension_type"]
dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"]
def test_types(self):
self.check(types, self.allowed + self.dtypes + self.deprecated)
def test_deprecated_from_api_types(self):
Reported by Pylint.
Line: 59
Column: 5
self.check(types, self.allowed + self.dtypes + self.deprecated)
def test_deprecated_from_api_types(self):
for t in self.deprecated:
with tm.assert_produces_warning(FutureWarning):
getattr(types, t)(1)
Reported by Pylint.
Line: 61
Column: 13
def test_deprecated_from_api_types(self):
for t in self.deprecated:
with tm.assert_produces_warning(FutureWarning):
getattr(types, t)(1)
Reported by Pylint.
pandas/plotting/_matplotlib/__init__.py
5 issues
Line: 1
Column: 1
from __future__ import annotations
from typing import TYPE_CHECKING
from pandas.plotting._matplotlib.boxplot import (
BoxPlot,
boxplot,
boxplot_frame,
boxplot_frame_groupby,
Reported by Pylint.
Line: 58
Column: 1
}
def plot(data, kind, **kwargs):
# Importing pyplot at the top of the file (before the converters are
# registered) causes problems in matplotlib 2 (converters seem to not
# work)
import matplotlib.pyplot as plt
Reported by Pylint.
Line: 62
Column: 5
# Importing pyplot at the top of the file (before the converters are
# registered) causes problems in matplotlib 2 (converters seem to not
# work)
import matplotlib.pyplot as plt
if kwargs.pop("reuse_plot", False):
ax = kwargs.get("ax")
if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
Reported by Pylint.
Line: 65
Column: 9
import matplotlib.pyplot as plt
if kwargs.pop("reuse_plot", False):
ax = kwargs.get("ax")
if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
ax = plt.gca()
kwargs["ax"] = getattr(ax, "left_ax", ax)
plot_obj = PLOT_CLASSES[kind](data, **kwargs)
Reported by Pylint.
Line: 68
Column: 17
ax = kwargs.get("ax")
if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
ax = plt.gca()
kwargs["ax"] = getattr(ax, "left_ax", ax)
plot_obj = PLOT_CLASSES[kind](data, **kwargs)
plot_obj.generate()
plot_obj.draw()
return plot_obj.result
Reported by Pylint.
pandas/tests/extension/arrow/test_string.py
5 issues
Line: 1
Column: 1
import pytest
import pandas as pd
pytest.importorskip("pyarrow", minversion="1.0.0")
def test_constructor_from_list():
# GH 27673
Reported by Pylint.
Line: 1
Column: 1
import pytest
import pandas as pd
pytest.importorskip("pyarrow", minversion="1.0.0")
def test_constructor_from_list():
# GH 27673
Reported by Pylint.
Line: 8
Column: 1
pytest.importorskip("pyarrow", minversion="1.0.0")
def test_constructor_from_list():
# GH 27673
result = pd.Series(["E"], dtype=pd.StringDtype(storage="pyarrow"))
assert isinstance(result.dtype, pd.StringDtype)
assert result.dtype.storage == "pyarrow"
Reported by Pylint.
Line: 11
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_constructor_from_list():
# GH 27673
result = pd.Series(["E"], dtype=pd.StringDtype(storage="pyarrow"))
assert isinstance(result.dtype, pd.StringDtype)
assert result.dtype.storage == "pyarrow"
Reported by Bandit.
Line: 12
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
# GH 27673
result = pd.Series(["E"], dtype=pd.StringDtype(storage="pyarrow"))
assert isinstance(result.dtype, pd.StringDtype)
assert result.dtype.storage == "pyarrow"
Reported by Bandit.
pandas/tests/base/test_fillna.py
5 issues
Line: 7
Column: 1
"""
import numpy as np
import pytest
from pandas._libs import iNaT
from pandas.core.dtypes.common import needs_i8_conversion
from pandas.core.dtypes.generic import ABCMultiIndex
Reported by Pylint.
Line: 19
Column: 1
from pandas.tests.base.common import allow_na_ops
def test_fillna(index_or_series_obj):
# GH 11343
obj = index_or_series_obj
if isinstance(obj, ABCMultiIndex):
pytest.skip("MultiIndex doesn't support isna")
Reported by Pylint.
Line: 34
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
tm.assert_series_equal(obj, result)
# check shallow_copied
assert obj is not result
@pytest.mark.parametrize("null_obj", [np.nan, None])
def test_fillna_null(null_obj, index_or_series_obj):
# GH 11343
Reported by Bandit.
Line: 38
Column: 1
@pytest.mark.parametrize("null_obj", [np.nan, None])
def test_fillna_null(null_obj, index_or_series_obj):
# GH 11343
obj = index_or_series_obj
klass = type(obj)
if not allow_na_ops(obj):
Reported by Pylint.
Line: 70
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
tm.assert_series_equal(result, expected)
# check shallow_copied
assert obj is not result
Reported by Bandit.
pandas/plotting/_matplotlib/groupby.py
5 issues
Line: 1
Column: 1
from __future__ import annotations
import numpy as np
from pandas._typing import (
Dict,
IndexLabel,
)
Reported by Pylint.
Line: 67
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
# Select sub-columns based on the value of level of MI, and if `by` is
# assigned, data must be a MI DataFrame
assert isinstance(data.columns, MultiIndex)
return {
col: data.loc[:, data.columns.get_level_values(level) == col]
for col in data.columns.levels[level]
}
Reported by Bandit.
Line: 74
Column: 1
}
def reconstruct_data_with_by(
data: DataFrame, by: IndexLabel, cols: IndexLabel
) -> DataFrame:
"""
Internal function to group data, and reassign multiindex column names onto the
result in order to let grouped data be used in _compute_plot_data method.
Reported by Pylint.
Line: 117
Column: 1
return data
def reformat_hist_y_given_by(
y: Series | np.ndarray, by: IndexLabel | None
) -> Series | np.ndarray:
"""Internal function to reformat y given `by` is applied or not for hist plot.
If by is None, input y is 1-d with NaN removed; and if by is not None, groupby
Reported by Pylint.
Line: 117
Column: 1
return data
def reformat_hist_y_given_by(
y: Series | np.ndarray, by: IndexLabel | None
) -> Series | np.ndarray:
"""Internal function to reformat y given `by` is applied or not for hist plot.
If by is None, input y is 1-d with NaN removed; and if by is not None, groupby
Reported by Pylint.
pandas/core/aggregation.py
5 issues
Line: 153
Column: 3
"""
# Normalize the aggregation functions as Mapping[column, List[func]],
# process normally, then fixup the names.
# TODO: aggspec type: typing.Dict[str, List[AggScalar]]
# May be hitting https://github.com/python/mypy/issues/5958
# saying it doesn't have an attribute __name__
aggspec: DefaultDict = defaultdict(list)
order = []
columns, pairs = list(zip(*kwargs.items()))
Reported by Pylint.
Line: 204
Column: 3
]
# TODO: Can't use, because mypy doesn't like us setting __name__
# error: "partial[Any]" has no attribute "__name__"
# the type is:
# typing.Sequence[Callable[..., ScalarResult]]
# -> typing.Sequence[Callable[..., ScalarResult]]:
Reported by Pylint.
Line: 83
Column: 9
order: list[int] | None = None
if not relabeling:
if isinstance(func, list) and len(func) > len(set(func)):
# GH 28426 will raise error if duplicated function names are used and
# there is no reassigned name
raise SpecificationError(
"Function names must be unique if there is no new column names "
Reported by Pylint.
Line: 325
Column: 9
reorder_mask = not isinstance(result, ABCSeries) and len(result.columns) > 1
for col, fun in func.items():
s = result[col].dropna()
# In the `_aggregate`, the callable names are obtained and used in `result`, and
# these names are ordered alphabetically. e.g.
# C2 C1
# <lambda> 1 NaN
Reported by Pylint.
Line: 352
Column: 13
com.get_callable_name(f) if not isinstance(f, str) else f for f in fun
]
col_idx_order = Index(s.index).get_indexer(fun)
s = s[col_idx_order]
# assign the new user-provided "named aggregation" as index names, and reindex
# it based on the whole user-provided names.
s.index = reordered_indexes[idx : idx + len(fun)]
reordered_result_in_dict[col] = s.reindex(columns, copy=False)
Reported by Pylint.