Skip to content

STYLE: fix some consider-using-enumerate pylint warnings #49214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions pandas/core/array_algos/take.py
Original file line number Diff line number Diff line change
Expand Up @@ -549,13 +549,9 @@ def _take_2d_multi_object(
out[row_mask, :] = fill_value
if col_needs:
out[:, col_mask] = fill_value
for i in range(len(row_idx)):
u_ = row_idx[i]

for i, u_ in enumerate(row_idx):
if u_ != -1:
for j in range(len(col_idx)):
v = col_idx[j]

for j, v in enumerate(col_idx):
if v != -1:
out[i, j] = arr[u_, v]

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1438,11 +1438,11 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
closed = self.closed

result = np.empty(len(left), dtype=object)
for i in range(len(left)):
for i, left_value in enumerate(left):
if mask[i]:
result[i] = np.nan
else:
result[i] = Interval(left[i], right[i], closed)
result[i] = Interval(left_value, right[i], closed)
return result

def __arrow_array__(self, type=None):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5762,11 +5762,11 @@ def _replace_columnwise(
res = self if inplace else self.copy()
ax = self.columns

for i in range(len(ax)):
if ax[i] in mapping:
for i, ax_value in enumerate(ax):
if ax_value in mapping:
ser = self.iloc[:, i]

target, value = mapping[ax[i]]
target, value = mapping[ax_value]
newobj = ser.replace(target, value, regex=regex)

res._iset_item(i, newobj)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2889,11 +2889,11 @@ def blk_func(values: ArrayLike) -> ArrayLike:
else:
out = type(values)._empty(values.shape, dtype=values.dtype)

for i in range(len(values)):
for i, value_element in enumerate(values):
# call group_fillna_indexer column-wise
indexer = np.empty(values.shape[1], dtype=np.intp)
col_func(out=indexer, mask=mask[i])
out[i, :] = algorithms.take_nd(values[i], indexer)
out[i, :] = algorithms.take_nd(value_element, indexer)
return out

obj = self._obj_with_exclusions
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2152,12 +2152,12 @@ def _get_multiindex_indexer(
rcodes = list(map(i8copy, index.codes))

# fix right labels if there were any nulls
for i in range(len(join_keys)):
for i, join_key in enumerate(join_keys):
mask = index.codes[i] == -1
if mask.any():
# check if there already was any nulls at this location
# if there was, it is factorized to `shape[i] - 1`
a = join_keys[i][lcodes[i] == shape[i] - 1]
a = join_key[lcodes[i] == shape[i] - 1]
if a.size == 0 or not a[0] != a[0]:
shape[i] += 1

Expand Down
18 changes: 5 additions & 13 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,8 @@ def _unstack_multiple(data, clocs, fill_value=None):
else:
if isinstance(data.columns, MultiIndex):
result = data
for i in range(len(clocs)):
val = clocs[i]
while clocs:
val = clocs.pop(0)
result = result.unstack(val, fill_value=fill_value)
clocs = [v if v < val else v - 1 for v in clocs]

Expand Down Expand Up @@ -634,20 +634,12 @@ def stack_multiple(frame, level, dropna: bool = True):
# negative numbers to positive
level = [frame.columns._get_level_number(lev) for lev in level]

# Can't iterate directly through level as we might need to change
# values as we go
for index in range(len(level)):
lev = level[index]
while level:
lev = level.pop(0)
result = stack(result, lev, dropna=dropna)
# Decrement all level numbers greater than current, as these
# have now shifted down by one
updated_level = []
for other in level:
if other > lev:
updated_level.append(other - 1)
else:
updated_level.append(other)
level = updated_level
level = [v if v <= lev else v - 1 for v in level]
Comment on lines -639 to +642
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Looks fine, and I ran

$ cat f.py 
import numpy as np

for _ in range(10):

    original_level = np.random.randint(0, 8, size=9)

    main_lev_sequence = []
    level = [i for i in original_level]
    for index in range(len(level)):
        lev = level[index]
        main_lev_sequence.append(lev)
        updated_level = []
        for other in level:
            if other > lev:
                updated_level.append(other - 1)
            else:
                updated_level.append(other)
        level = updated_level

    branch_lev_sequence = []
    level = [i for i in original_level]
    while level:
        lev = level.pop(0)
        branch_lev_sequence.append(lev)
        level = [v if v <= lev else v - 1 for v in level]

    assert main_lev_sequence == branch_lev_sequence

to check, which worked


else:
raise ValueError(
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ def _write_hierarchical_rows(
level_lengths[lnum] = rec_new

level_lengths[inner_lvl][ins_row] = 1
for ix_col in range(len(fmt_values)):
for ix_col in fmt_values:
fmt_values[ix_col].insert(ins_row, "...")
nrows += 1

Expand Down
8 changes: 4 additions & 4 deletions pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,17 +426,17 @@ def best_len(values: list[str]) -> int:
summary = ""
line = space2

for max_items in range(len(head)):
word = head[max_items] + sep + " "
for head_value in head:
word = head_value + sep + " "
summary, line = _extend_line(summary, line, word, display_width, space2)

if is_truncated:
# remove trailing space of last line
summary += line.rstrip() + space2 + "..."
line = space2

for max_items in range(len(tail) - 1):
word = tail[max_items] + sep + " "
for tail_item in tail[:-1]:
word = tail_item + sep + " "
summary, line = _extend_line(summary, line, word, display_width, space2)

# last value: no sep added + 1 space of width used for trailing ','
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/arrays/sparse/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
class TestGetitem:
def test_getitem(self):
dense = arr.to_dense()
for i in range(len(arr)):
tm.assert_almost_equal(arr[i], dense[i])
for i, value in enumerate(arr):
tm.assert_almost_equal(value, dense[i])
tm.assert_almost_equal(arr[-i], dense[-i])

def test_getitem_arraylike_mask(self):
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,8 +873,8 @@ def test_replace_input_formats_listlike(self):
values = [-2, -1, "missing"]
result = df.replace(to_rep, values)
expected = df.copy()
for i in range(len(to_rep)):
return_value = expected.replace(to_rep[i], values[i], inplace=True)
for rep, value in zip(to_rep, values):
return_value = expected.replace(rep, value, inplace=True)
assert return_value is None
tm.assert_frame_equal(result, expected)

Expand All @@ -901,8 +901,8 @@ def test_replace_input_formats_scalar(self):
to_rep = [np.nan, 0, ""]
result = df.replace(to_rep, -1)
expected = df.copy()
for i in range(len(to_rep)):
return_value = expected.replace(to_rep[i], -1, inplace=True)
for rep in to_rep:
return_value = expected.replace(rep, -1, inplace=True)
assert return_value is None
tm.assert_frame_equal(result, expected)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/multi/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,9 +884,9 @@ def test_pyint_engine():
# keys would collide; if truncating the last levels, the fifth and
# sixth; if rotating bits rather than shifting, the third and fifth.

for idx in range(len(keys)):
for idx, key_value in enumerate(keys):
index = MultiIndex.from_tuples(keys)
assert index.get_loc(keys[idx]) == idx
assert index.get_loc(key_value) == idx

expected = np.arange(idx + 1, dtype=np.intp)
result = index.get_indexer([keys[i] for i in expected])
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/io/test_stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,15 +774,15 @@ def test_big_dates(self, datapath):
mm = [0, 0, 59, 0, 0, 0]
ss = [0, 0, 59, 0, 0, 0]
expected = []
for i in range(len(yr)):
for year, month, day, hour, minute, second in zip(yr, mo, dd, hr, mm, ss):
row = []
for j in range(7):
if j == 0:
row.append(datetime(yr[i], mo[i], dd[i], hr[i], mm[i], ss[i]))
row.append(datetime(year, month, day, hour, minute, second))
elif j == 6:
row.append(datetime(yr[i], 1, 1))
row.append(datetime(year, 1, 1))
else:
row.append(datetime(yr[i], mo[i], dd[i]))
row.append(datetime(year, month, day))
expected.append(row)
expected.append([pd.NaT] * 7)
columns = [
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/series/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def test_setitem_scalar_into_readonly_backing_data():
array.flags.writeable = False # make the array immutable
series = Series(array)

for n in range(len(series)):
for n in series.index:
msg = "assignment destination is read-only"
with pytest.raises(ValueError, match=msg):
series[n] = 1
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ disable = [
# pylint type "C": convention, for programming standard violation
"consider-iterating-dictionary",
"consider-using-dict-items",
"consider-using-enumerate",
"consider-using-f-string",
"disallowed-name",
"import-outside-toplevel",
Expand Down