Skip to content

Commit 8ac3123

Browse files
topper-123jschendel
authored andcommitted
CLN: remove uses of compat.lrange, part I (#26281)
1 parent 560ad35 commit 8ac3123

File tree

17 files changed

+45
-55
lines changed

17 files changed

+45
-55
lines changed

pandas/core/generic.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from pandas._config import config
1616

1717
from pandas._libs import Timestamp, iNaT, properties
18-
from pandas.compat import lrange, lzip, set_function_name, to_str
18+
from pandas.compat import lzip, set_function_name, to_str
1919
from pandas.compat.numpy import function as nv
2020
from pandas.errors import AbstractMethodError
2121
from pandas.util._decorators import (
@@ -1101,7 +1101,7 @@ def rename(self, *args, **kwargs):
11011101
result = self if inplace else self.copy(deep=copy)
11021102

11031103
# start in the axis order to eliminate too many copies
1104-
for axis in lrange(self._AXIS_LEN):
1104+
for axis in range(self._AXIS_LEN):
11051105
v = axes.get(self._AXIS_NAMES[axis])
11061106
if v is None:
11071107
continue
@@ -1294,7 +1294,7 @@ class name
12941294
# is specified
12951295
result = self if inplace else self.copy(deep=copy)
12961296

1297-
for axis in lrange(self._AXIS_LEN):
1297+
for axis in range(self._AXIS_LEN):
12981298
v = axes.get(self._AXIS_NAMES[axis])
12991299
if v is sentinel:
13001300
continue

pandas/core/indexes/multi.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas._libs import (
1111
Timestamp, algos as libalgos, index as libindex, lib, tslibs)
12-
from pandas.compat import lrange, lzip
12+
from pandas.compat import lzip
1313
from pandas.compat.numpy import function as nv
1414
from pandas.errors import PerformanceWarning, UnsortedIndexError
1515
from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg
@@ -1913,7 +1913,7 @@ def drop(self, codes, level=None, errors='raise'):
19131913
if isinstance(loc, int):
19141914
inds.append(loc)
19151915
elif isinstance(loc, slice):
1916-
inds.extend(lrange(loc.start, loc.stop))
1916+
inds.extend(range(loc.start, loc.stop))
19171917
elif com.is_bool_indexer(loc):
19181918
if self.lexsort_depth == 0:
19191919
warnings.warn('dropping on a non-lexsorted multi-index'

pandas/core/indexes/range.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
from pandas._libs import index as libindex, lib
99
import pandas.compat as compat
10-
from pandas.compat import lrange
1110
from pandas.compat.numpy import function as nv
1211
from pandas.util._decorators import Appender, cache_readonly
1312

@@ -292,7 +291,7 @@ def has_duplicates(self):
292291
return False
293292

294293
def tolist(self):
295-
return lrange(self._start, self._stop, self._step)
294+
return list(range(self._start, self._stop, self._step))
296295

297296
@Appender(_index_shared_docs['_shallow_copy'])
298297
def _shallow_copy(self, values=None, **kwargs):

pandas/core/internals/construction.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas._libs import lib
1111
from pandas._libs.tslibs import IncompatibleFrequency
12-
from pandas.compat import lmap, lrange, raise_with_traceback
12+
from pandas.compat import lmap, raise_with_traceback
1313

1414
from pandas.core.dtypes.cast import (
1515
construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na,
@@ -339,7 +339,7 @@ def get_names_from_index(data):
339339
if not has_some_name:
340340
return ibase.default_index(len(data))
341341

342-
index = lrange(len(data))
342+
index = list(range(len(data)))
343343
count = 0
344344
for i, s in enumerate(data):
345345
n = getattr(s, 'name', None)

pandas/core/reshape/concat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ def _get_new_axes(self):
452452
"to {length}".format(length=ndim - 1))
453453

454454
# ufff...
455-
indices = compat.lrange(ndim)
455+
indices = list(range(ndim))
456456
indices.remove(self.axis)
457457

458458
for i, ax in zip(indices, self.join_axes):

pandas/core/reshape/pivot.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import numpy as np
22

3-
from pandas.compat import lrange
43
from pandas.util._decorators import Appender, Substitution
54

65
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
@@ -303,7 +302,7 @@ def _all_key(key):
303302
row_margin = row_margin.stack()
304303

305304
# slight hack
306-
new_order = [len(cols)] + lrange(len(cols))
305+
new_order = [len(cols)] + list(range(len(cols)))
307306
row_margin.index = row_margin.index.reorder_levels(new_order)
308307
else:
309308
row_margin = Series(np.nan, index=result.columns)

pandas/io/excel/_util.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import warnings
22

3-
from pandas.compat import lrange
4-
53
from pandas.core.dtypes.common import is_integer, is_list_like
64

75
_writers = {}
@@ -112,7 +110,7 @@ def _range2cols(areas):
112110
for rng in areas.split(","):
113111
if ":" in rng:
114112
rng = rng.split(":")
115-
cols.extend(lrange(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
113+
cols.extend(range(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
116114
else:
117115
cols.append(_excel2num(rng))
118116

@@ -141,7 +139,7 @@ def _maybe_convert_usecols(usecols):
141139
"deprecated. Please pass in a list of int from "
142140
"0 to `usecols` inclusive instead."),
143141
FutureWarning, stacklevel=2)
144-
return lrange(usecols + 1)
142+
return list(range(usecols + 1))
145143

146144
if isinstance(usecols, str):
147145
return _range2cols(usecols)

pandas/io/html.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import os
1010
import re
1111

12-
from pandas.compat import lmap, lrange, raise_with_traceback
12+
from pandas.compat import lmap, raise_with_traceback
1313
from pandas.errors import AbstractMethodError, EmptyDataError
1414

1515
from pandas.core.dtypes.common import is_list_like
@@ -101,7 +101,8 @@ def _get_skiprows(skiprows):
101101
A proper iterator to use to skip rows of a DataFrame.
102102
"""
103103
if isinstance(skiprows, slice):
104-
return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
104+
start, step = skiprows.start or 0, skiprows.step or 1
105+
return list(range(start, skiprows.stop, step))
105106
elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
106107
return skiprows
107108
elif skiprows is None:

pandas/io/pytables.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818

1919
from pandas._libs import lib, writers as libwriters
2020
from pandas._libs.tslibs import timezones
21-
from pandas.compat import lrange
2221
from pandas.errors import PerformanceWarning
2322

2423
from pandas.core.dtypes.common import (
@@ -4101,7 +4100,7 @@ def delete(self, where=None, start=None, stop=None, **kwargs):
41014100
# we must remove in reverse order!
41024101
pg = groups.pop()
41034102
for g in reversed(groups):
4104-
rows = sorted_series.take(lrange(g, pg))
4103+
rows = sorted_series.take(range(g, pg))
41054104
table.remove_rows(start=rows[rows.index[0]
41064105
], stop=rows[rows.index[-1]] + 1)
41074106
pg = g

pandas/io/stata.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
from pandas._libs.lib import infer_dtype
2525
from pandas._libs.writers import max_len_string_array
26-
from pandas.compat import lmap, lrange, lzip
26+
from pandas.compat import lmap, lzip
2727
from pandas.util._decorators import Appender, deprecate_kwarg
2828

2929
from pandas.core.dtypes.common import (
@@ -874,7 +874,7 @@ def __init__(self):
874874
(65530, np.int8)
875875
]
876876
)
877-
self.TYPE_MAP = lrange(251) + list('bhlfd')
877+
self.TYPE_MAP = list(range(251)) + list('bhlfd')
878878
self.TYPE_MAP_XML = \
879879
dict(
880880
[

pandas/tests/groupby/test_apply.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import pytest
66

77
import pandas as pd
8-
from pandas import DataFrame, Index, MultiIndex, Series, bdate_range, compat
8+
from pandas import DataFrame, Index, MultiIndex, Series, bdate_range
99
from pandas.util import testing as tm
1010

1111

@@ -340,7 +340,7 @@ def f(group):
340340
def test_apply_chunk_view():
341341
# Low level tinkering could be unsafe, make sure not
342342
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
343-
'value': compat.lrange(9)})
343+
'value': range(9)})
344344

345345
result = df.groupby('key', group_keys=False).apply(lambda x: x[:2])
346346
expected = df.take([0, 1, 3, 4, 6, 7])
@@ -350,7 +350,7 @@ def test_apply_chunk_view():
350350
def test_apply_no_name_column_conflict():
351351
df = DataFrame({'name': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],
352352
'name2': [0, 0, 0, 1, 1, 1, 0, 0, 1, 1],
353-
'value': compat.lrange(10)[::-1]})
353+
'value': range(9, -1, -1)})
354354

355355
# it works! #2605
356356
grouped = df.groupby(['name', 'name2'])

pandas/tests/groupby/test_groupby.py

+12-13
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import numpy as np
77
import pytest
88

9-
from pandas.compat import lmap, lrange, lzip
9+
from pandas.compat import lmap, lzip
1010
from pandas.errors import PerformanceWarning
1111

1212
import pandas as pd
@@ -84,7 +84,7 @@ def test_groupby_nonobject_dtype(mframe, df_mixed_floats):
8484

8585
# GH 3911, mixed frame non-conversion
8686
df = df_mixed_floats.copy()
87-
df['value'] = lrange(len(df))
87+
df['value'] = range(len(df))
8888

8989
def max_value(group):
9090
return group.loc[group['value'].idxmax()]
@@ -249,11 +249,10 @@ def test_len():
249249

250250
def test_basic_regression():
251251
# regression
252-
T = [1.0 * x for x in lrange(1, 10) * 10][:1095]
253-
result = Series(T, lrange(0, len(T)))
252+
result = Series([1.0 * x for x in list(range(1, 10)) * 10])
254253

255-
groupings = np.random.random((1100, ))
256-
groupings = Series(groupings, lrange(0, len(groupings))) * 10.
254+
data = np.random.random(1100) * 10.
255+
groupings = Series(data)
257256

258257
grouped = result.groupby(groupings)
259258
grouped.mean()
@@ -320,9 +319,9 @@ def f3(x):
320319
else:
321320
return y
322321

323-
df = DataFrame({'a': [1, 2, 2, 2], 'b': lrange(4), 'c': lrange(5, 9)})
322+
df = DataFrame({'a': [1, 2, 2, 2], 'b': range(4), 'c': range(5, 9)})
324323

325-
df2 = DataFrame({'a': [3, 2, 2, 2], 'b': lrange(4), 'c': lrange(5, 9)})
324+
df2 = DataFrame({'a': [3, 2, 2, 2], 'b': range(4), 'c': range(5, 9)})
326325

327326
# correct result
328327
result1 = df.groupby('a').apply(f1)
@@ -875,7 +874,7 @@ def test_mutate_groups():
875874
'cat1': ['a'] * 8 + ['b'] * 6,
876875
'cat2': ['c'] * 2 + ['d'] * 2 + ['e'] * 2 + ['f'] * 2 + ['c'] * 2 +
877876
['d'] * 2 + ['e'] * 2,
878-
'cat3': lmap(lambda x: 'g%s' % x, lrange(1, 15)),
877+
'cat3': lmap(lambda x: 'g%s' % x, range(1, 15)),
879878
'val': np.random.randint(100, size=14),
880879
})
881880

@@ -1063,8 +1062,8 @@ def test_groupby_mixed_type_columns():
10631062
def test_cython_grouper_series_bug_noncontig():
10641063
arr = np.empty((100, 100))
10651064
arr.fill(np.nan)
1066-
obj = Series(arr[:, 0], index=lrange(100))
1067-
inds = np.tile(lrange(10), 10)
1065+
obj = Series(arr[:, 0])
1066+
inds = np.tile(range(10), 10)
10681067

10691068
result = obj.groupby(inds).agg(Series.median)
10701069
assert result.isna().all()
@@ -1086,7 +1085,7 @@ def test_series_grouper_noncontig_index():
10861085

10871086
def test_convert_objects_leave_decimal_alone():
10881087

1089-
s = Series(lrange(5))
1088+
s = Series(range(5))
10901089
labels = np.array(['a', 'b', 'c', 'd', 'e'], dtype='O')
10911090

10921091
def convert_fast(x):
@@ -1217,7 +1216,7 @@ def test_groupby_nat_exclude():
12171216

12181217

12191218
def test_groupby_2d_malformed():
1220-
d = DataFrame(index=lrange(2))
1219+
d = DataFrame(index=range(2))
12211220
d['group'] = ['g1', 'g2']
12221221
d['zeros'] = [0, 0]
12231222
d['ones'] = [1, 1]

pandas/tests/groupby/test_grouping.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import numpy as np
44
import pytest
55

6-
from pandas.compat import lrange
7-
86
import pandas as pd
97
from pandas import (
108
CategoricalIndex, DataFrame, Index, MultiIndex, Series, Timestamp,
@@ -481,7 +479,7 @@ def test_groupby_level(self, sort, mframe, df):
481479
def test_groupby_level_index_names(self):
482480
# GH4014 this used to raise ValueError since 'exp'>1 (in py2)
483481
df = DataFrame({'exp': ['A'] * 3 + ['B'] * 3,
484-
'var1': lrange(6), }).set_index('exp')
482+
'var1': range(6), }).set_index('exp')
485483
df.groupby(level='exp')
486484
msg = "level name foo is not the name of the index"
487485
with pytest.raises(ValueError, match=msg):

pandas/tests/groupby/test_nth.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import numpy as np
22
import pytest
33

4-
from pandas.compat import lrange
5-
64
import pandas as pd
75
from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna
86
from pandas.util.testing import (
@@ -84,9 +82,9 @@ def test_first_last_nth_dtypes(df_mixed_floats):
8482
assert_frame_equal(nth, expected)
8583

8684
# GH 2763, first/last shifting dtypes
87-
idx = lrange(10)
85+
idx = list(range(10))
8886
idx.append(9)
89-
s = Series(data=lrange(11), index=idx, name='IntCol')
87+
s = Series(data=range(11), index=idx, name='IntCol')
9088
assert s.dtype == 'int64'
9189
f = s.groupby(level=0).first()
9290
assert f.dtype == 'int64'

pandas/tests/indexes/multi/test_sorting.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import numpy as np
22
import pytest
33

4-
from pandas.compat import lrange
54
from pandas.errors import PerformanceWarning, UnsortedIndexError
65

76
import pandas as pd
@@ -97,7 +96,7 @@ def test_unsortedindex():
9796
mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
9897
('x', 'b'), ('y', 'a'), ('z', 'b')],
9998
names=['one', 'two'])
100-
df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi,
99+
df = pd.DataFrame([[i, 10 * i] for i in range(6)], index=mi,
101100
columns=['one', 'two'])
102101

103102
# GH 16734: not sorted, but no real slicing

pandas/tests/test_multilevel.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import pytest
1010
import pytz
1111

12-
from pandas.compat import lrange, lzip
12+
from pandas.compat import lzip
1313

1414
from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
1515

@@ -127,8 +127,8 @@ def test_series_constructor(self):
127127
multi = Series(1., index=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']])
128128
assert isinstance(multi.index, MultiIndex)
129129

130-
multi = Series(lrange(4), index=[['a', 'a', 'b', 'b'],
131-
['x', 'y', 'x', 'y']])
130+
multi = Series(range(4), index=[['a', 'a', 'b', 'b'],
131+
['x', 'y', 'x', 'y']])
132132
assert isinstance(multi.index, MultiIndex)
133133

134134
def test_reindex_level(self):
@@ -1317,7 +1317,7 @@ def test_unicode_repr_level_names(self):
13171317
index = MultiIndex.from_tuples([(0, 0), (1, 1)],
13181318
names=['\u0394', 'i1'])
13191319

1320-
s = Series(lrange(2), index=index)
1320+
s = Series(range(2), index=index)
13211321
df = DataFrame(np.random.randn(2, 4), index=index)
13221322
repr(s)
13231323
repr(df)

0 commit comments

Comments
 (0)