Skip to content

CLN: remove uses of compat.lrange, part I #26281

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 3 commits into from
May 5, 2019
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
6 changes: 3 additions & 3 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from pandas._config import config

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

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

for axis in lrange(self._AXIS_LEN):
for axis in range(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
if v is sentinel:
continue
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from pandas._libs import (
Timestamp, algos as libalgos, index as libindex, lib, tslibs)
from pandas.compat import lrange, lzip
from pandas.compat import lzip
from pandas.compat.numpy import function as nv
from pandas.errors import PerformanceWarning, UnsortedIndexError
from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg
Expand Down Expand Up @@ -1913,7 +1913,7 @@ def drop(self, codes, level=None, errors='raise'):
if isinstance(loc, int):
inds.append(loc)
elif isinstance(loc, slice):
inds.extend(lrange(loc.start, loc.stop))
inds.extend(range(loc.start, loc.stop))
elif com.is_bool_indexer(loc):
if self.lexsort_depth == 0:
warnings.warn('dropping on a non-lexsorted multi-index'
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from pandas._libs import index as libindex, lib
import pandas.compat as compat
from pandas.compat import lrange
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, cache_readonly

Expand Down Expand Up @@ -292,7 +291,7 @@ def has_duplicates(self):
return False

def tolist(self):
return lrange(self._start, self._stop, self._step)
return list(range(self._start, self._stop, self._step))

@Appender(_index_shared_docs['_shallow_copy'])
def _shallow_copy(self, values=None, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from pandas._libs import lib
from pandas._libs.tslibs import IncompatibleFrequency
from pandas.compat import lmap, lrange, raise_with_traceback
from pandas.compat import lmap, raise_with_traceback

from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na,
Expand Down Expand Up @@ -339,7 +339,7 @@ def get_names_from_index(data):
if not has_some_name:
return ibase.default_index(len(data))

index = lrange(len(data))
index = list(range(len(data)))
count = 0
for i, s in enumerate(data):
n = getattr(s, 'name', None)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/reshape/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ def _get_new_axes(self):
"to {length}".format(length=ndim - 1))

# ufff...
indices = compat.lrange(ndim)
indices = list(range(ndim))
indices.remove(self.axis)

for i, ax in zip(indices, self.join_axes):
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import numpy as np

from pandas.compat import lrange
from pandas.util._decorators import Appender, Substitution

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

# slight hack
new_order = [len(cols)] + lrange(len(cols))
new_order = [len(cols)] + list(range(len(cols)))
row_margin.index = row_margin.index.reorder_levels(new_order)
else:
row_margin = Series(np.nan, index=result.columns)
Expand Down
6 changes: 2 additions & 4 deletions pandas/io/excel/_util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import warnings

from pandas.compat import lrange

from pandas.core.dtypes.common import is_integer, is_list_like

_writers = {}
Expand Down Expand Up @@ -112,7 +110,7 @@ def _range2cols(areas):
for rng in areas.split(","):
if ":" in rng:
rng = rng.split(":")
cols.extend(lrange(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
cols.extend(range(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
else:
cols.append(_excel2num(rng))

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

if isinstance(usecols, str):
return _range2cols(usecols)
Expand Down
5 changes: 3 additions & 2 deletions pandas/io/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import os
import re

from pandas.compat import lmap, lrange, raise_with_traceback
from pandas.compat import lmap, raise_with_traceback
from pandas.errors import AbstractMethodError, EmptyDataError

from pandas.core.dtypes.common import is_list_like
Expand Down Expand Up @@ -101,7 +101,8 @@ def _get_skiprows(skiprows):
A proper iterator to use to skip rows of a DataFrame.
"""
if isinstance(skiprows, slice):
return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
start, step = skiprows.start or 0, skiprows.step or 1
return list(range(start, skiprows.stop, step))
elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
return skiprows
elif skiprows is None:
Expand Down
3 changes: 1 addition & 2 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

from pandas._libs import lib, writers as libwriters
from pandas._libs.tslibs import timezones
from pandas.compat import lrange
from pandas.errors import PerformanceWarning

from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -4101,7 +4100,7 @@ def delete(self, where=None, start=None, stop=None, **kwargs):
# we must remove in reverse order!
pg = groups.pop()
for g in reversed(groups):
rows = sorted_series.take(lrange(g, pg))
rows = sorted_series.take(range(g, pg))
table.remove_rows(start=rows[rows.index[0]
], stop=rows[rows.index[-1]] + 1)
pg = g
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from pandas._libs.lib import infer_dtype
from pandas._libs.writers import max_len_string_array
from pandas.compat import lmap, lrange, lzip
from pandas.compat import lmap, lzip
from pandas.util._decorators import Appender, deprecate_kwarg

from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -874,7 +874,7 @@ def __init__(self):
(65530, np.int8)
]
)
self.TYPE_MAP = lrange(251) + list('bhlfd')
self.TYPE_MAP = list(range(251)) + list('bhlfd')
self.TYPE_MAP_XML = \
dict(
[
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest

import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, bdate_range, compat
from pandas import DataFrame, Index, MultiIndex, Series, bdate_range
from pandas.util import testing as tm


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

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

# it works! #2605
grouped = df.groupby(['name', 'name2'])
Expand Down
25 changes: 12 additions & 13 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import numpy as np
import pytest

from pandas.compat import lmap, lrange, lzip
from pandas.compat import lmap, lzip
from pandas.errors import PerformanceWarning

import pandas as pd
Expand Down Expand Up @@ -84,7 +84,7 @@ def test_groupby_nonobject_dtype(mframe, df_mixed_floats):

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

def max_value(group):
return group.loc[group['value'].idxmax()]
Expand Down Expand Up @@ -249,11 +249,10 @@ def test_len():

def test_basic_regression():
# regression
T = [1.0 * x for x in lrange(1, 10) * 10][:1095]
result = Series(T, lrange(0, len(T)))
result = Series([1.0 * x for x in list(range(1, 10)) * 10])

groupings = np.random.random((1100, ))
groupings = Series(groupings, lrange(0, len(groupings))) * 10.
data = np.random.random(1100) * 10.
groupings = Series(data)

grouped = result.groupby(groupings)
grouped.mean()
Expand Down Expand Up @@ -320,9 +319,9 @@ def f3(x):
else:
return y

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

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

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

Expand Down Expand Up @@ -1063,8 +1062,8 @@ def test_groupby_mixed_type_columns():
def test_cython_grouper_series_bug_noncontig():
arr = np.empty((100, 100))
arr.fill(np.nan)
obj = Series(arr[:, 0], index=lrange(100))
inds = np.tile(lrange(10), 10)
obj = Series(arr[:, 0])
inds = np.tile(range(10), 10)

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

def test_convert_objects_leave_decimal_alone():

s = Series(lrange(5))
s = Series(range(5))
labels = np.array(['a', 'b', 'c', 'd', 'e'], dtype='O')

def convert_fast(x):
Expand Down Expand Up @@ -1217,7 +1216,7 @@ def test_groupby_nat_exclude():


def test_groupby_2d_malformed():
d = DataFrame(index=lrange(2))
d = DataFrame(index=range(2))
d['group'] = ['g1', 'g2']
d['zeros'] = [0, 0]
d['ones'] = [1, 1]
Expand Down
4 changes: 1 addition & 3 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import numpy as np
import pytest

from pandas.compat import lrange

import pandas as pd
from pandas import (
CategoricalIndex, DataFrame, Index, MultiIndex, Series, Timestamp,
Expand Down Expand Up @@ -481,7 +479,7 @@ def test_groupby_level(self, sort, mframe, df):
def test_groupby_level_index_names(self):
# GH4014 this used to raise ValueError since 'exp'>1 (in py2)
df = DataFrame({'exp': ['A'] * 3 + ['B'] * 3,
'var1': lrange(6), }).set_index('exp')
'var1': range(6), }).set_index('exp')
df.groupby(level='exp')
msg = "level name foo is not the name of the index"
with pytest.raises(ValueError, match=msg):
Expand Down
6 changes: 2 additions & 4 deletions pandas/tests/groupby/test_nth.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import numpy as np
import pytest

from pandas.compat import lrange

import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna
from pandas.util.testing import (
Expand Down Expand Up @@ -84,9 +82,9 @@ def test_first_last_nth_dtypes(df_mixed_floats):
assert_frame_equal(nth, expected)

# GH 2763, first/last shifting dtypes
idx = lrange(10)
idx = list(range(10))
idx.append(9)
s = Series(data=lrange(11), index=idx, name='IntCol')
s = Series(data=range(11), index=idx, name='IntCol')
assert s.dtype == 'int64'
f = s.groupby(level=0).first()
assert f.dtype == 'int64'
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/indexes/multi/test_sorting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import numpy as np
import pytest

from pandas.compat import lrange
from pandas.errors import PerformanceWarning, UnsortedIndexError

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

# GH 16734: not sorted, but no real slicing
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/test_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import pytest
import pytz

from pandas.compat import lrange, lzip
from pandas.compat import lzip

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

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

multi = Series(lrange(4), index=[['a', 'a', 'b', 'b'],
['x', 'y', 'x', 'y']])
multi = Series(range(4), index=[['a', 'a', 'b', 'b'],
['x', 'y', 'x', 'y']])
assert isinstance(multi.index, MultiIndex)

def test_reindex_level(self):
Expand Down Expand Up @@ -1317,7 +1317,7 @@ def test_unicode_repr_level_names(self):
index = MultiIndex.from_tuples([(0, 0), (1, 1)],
names=['\u0394', 'i1'])

s = Series(lrange(2), index=index)
s = Series(range(2), index=index)
df = DataFrame(np.random.randn(2, 4), index=index)
repr(s)
repr(df)
Expand Down
Loading