Skip to content

Commit 58fd449

Browse files
topper-123gfyoung
authored andcommitted
CLN: remove compat.lmap (#26322)
xref gh-25725
1 parent ee6b131 commit 58fd449

File tree

21 files changed

+84
-97
lines changed

21 files changed

+84
-97
lines changed

pandas/compat/__init__.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
Cross-compatible functions for different versions of Python.
66
77
Key items to import for compatible code:
8-
* lists: lrange(), lmap()
8+
* lists: lrange()
99
1010
Other items:
1111
* platform checker
@@ -24,10 +24,6 @@ def lrange(*args, **kwargs):
2424
return list(range(*args, **kwargs))
2525

2626

27-
def lmap(*args, **kwargs):
28-
return list(map(*args, **kwargs))
29-
30-
3127
# ----------------------------------------------------------------------------
3228
# functions largely based / taken from the six module
3329

pandas/core/computation/expr.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@
1111

1212
import numpy as np
1313

14-
from pandas.compat import lmap
15-
1614
import pandas as pd
1715
from pandas.core import common as com
1816
from pandas.core.base import StringMixin
@@ -180,7 +178,7 @@ def _preparse(source, f=_compose(_replace_locals, _replace_booleans,
180178
the ``tokenize`` module and ``tokval`` is a string.
181179
"""
182180
assert callable(f), 'f must be callable'
183-
return tokenize.untokenize(lmap(f, tokenize_string(source)))
181+
return tokenize.untokenize((f(x) for x in tokenize_string(source)))
184182

185183

186184
def _is_type(t):

pandas/core/frame.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from pandas.util._validators import (validate_bool_kwarg,
3232
validate_axis_style_args)
3333

34-
from pandas.compat import PY36, lmap, raise_with_traceback
34+
from pandas.compat import PY36, raise_with_traceback
3535
from pandas.compat.numpy import function as nv
3636
from pandas.core.dtypes.cast import (
3737
maybe_upcast,
@@ -1633,7 +1633,7 @@ def to_records(self, index=True, convert_datetime64=None,
16331633
else:
16341634
if isinstance(self.index, MultiIndex):
16351635
# array of tuples to numpy cols. copy copy copy
1636-
ix_vals = lmap(np.array, zip(*self.index.values))
1636+
ix_vals = list(map(np.array, zip(*self.index.values)))
16371637
else:
16381638
ix_vals = [self.index.values]
16391639

@@ -1650,10 +1650,11 @@ def to_records(self, index=True, convert_datetime64=None,
16501650
elif index_names[0] is None:
16511651
index_names = ['index']
16521652

1653-
names = lmap(str, index_names) + lmap(str, self.columns)
1653+
names = [str(name) for name in itertools.chain(index_names,
1654+
self.columns)]
16541655
else:
16551656
arrays = [self[c].get_values() for c in self.columns]
1656-
names = lmap(str, self.columns)
1657+
names = [str(c) for c in self.columns]
16571658
index_names = []
16581659

16591660
index_len = len(index_names)

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, raise_with_traceback
12+
from pandas.compat import raise_with_traceback
1313

1414
from pandas.core.dtypes.cast import (
1515
construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na,
@@ -413,7 +413,7 @@ def to_arrays(data, columns, coerce_float=False, dtype=None):
413413
return arrays, columns
414414
else:
415415
# last ditch effort
416-
data = lmap(tuple, data)
416+
data = [tuple(x) for x in data]
417417
return _list_to_arrays(data, columns, coerce_float=coerce_float,
418418
dtype=dtype)
419419

pandas/core/sparse/frame.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import numpy as np
88

99
from pandas._libs.sparse import BlockIndex, get_blocks
10-
from pandas.compat import lmap
1110
from pandas.compat.numpy import function as nv
1211
from pandas.util._decorators import Appender
1312

@@ -945,7 +944,7 @@ def applymap(self, func):
945944
-------
946945
applied : DataFrame
947946
"""
948-
return self.apply(lambda x: lmap(func, x))
947+
return self.apply(lambda x: [func(y) for y in x])
949948

950949

951950
def to_manager(sdf, columns, index):

pandas/core/sparse/scipy_sparse.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
"""
66
from collections import OrderedDict
77

8-
from pandas.compat import lmap
9-
108
from pandas.core.index import Index, MultiIndex
119
from pandas.core.series import Series
1210

@@ -53,7 +51,7 @@ def _get_label_to_i_dict(labels, sort_labels=False):
5351
""" Return OrderedDict of unique labels to number.
5452
Optionally sort by label.
5553
"""
56-
labels = Index(lmap(tuple, labels)).unique().tolist() # squish
54+
labels = Index(map(tuple, labels)).unique().tolist() # squish
5755
if sort_labels:
5856
labels = sorted(list(labels))
5957
d = OrderedDict((k, i) for i, k in enumerate(labels))

pandas/io/html.py

+2-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, raise_with_traceback
12+
from pandas.compat import raise_with_traceback
1313
from pandas.errors import AbstractMethodError, EmptyDataError
1414

1515
from pandas.core.dtypes.common import is_list_like
@@ -764,7 +764,7 @@ def _parse_tfoot_tr(self, table):
764764

765765

766766
def _expand_elements(body):
767-
lens = Series(lmap(len, body))
767+
lens = Series([len(elem) for elem in body])
768768
lens_max = lens.max()
769769
not_max = lens[lens != lens_max]
770770

pandas/io/stata.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
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
2726
from pandas.util._decorators import Appender, deprecate_kwarg
2827

2928
from pandas.core.dtypes.common import (
@@ -1030,7 +1029,7 @@ def _read_header(self):
10301029
if type(x) is int]) > 0
10311030

10321031
# calculate size of a data record
1033-
self.col_sizes = lmap(lambda x: self._calcsize(x), self.typlist)
1032+
self.col_sizes = [self._calcsize(typ) for typ in self.typlist]
10341033

10351034
def _read_new_header(self, first_char):
10361035
# The first part of the header is common to 117 and 118.
@@ -1573,9 +1572,9 @@ def read(self, nrows=None, convert_dates=None,
15731572
data = self._do_convert_missing(data, convert_missing)
15741573

15751574
if convert_dates:
1576-
cols = np.where(lmap(lambda x: any(x.startswith(fmt)
1577-
for fmt in _date_formats),
1578-
self.fmtlist))[0]
1575+
def any_startswith(x: str) -> bool:
1576+
return any(x.startswith(fmt) for fmt in _date_formats)
1577+
cols = np.where([any_startswith(x) for x in self.fmtlist])[0]
15791578
for i in cols:
15801579
col = data.columns[i]
15811580
try:

pandas/plotting/_misc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# being a bit too dynamic
22
import numpy as np
33

4-
from pandas.compat import lmap, lrange
4+
from pandas.compat import lrange
55
from pandas.util._decorators import deprecate_kwarg
66

77
from pandas.core.dtypes.missing import notna
@@ -625,7 +625,7 @@ def r(h):
625625
return ((data[:n - h] - mean) *
626626
(data[h:] - mean)).sum() / float(n) / c0
627627
x = np.arange(n) + 1
628-
y = lmap(r, x)
628+
y = [r(loc) for loc in x]
629629
z95 = 1.959963984540054
630630
z99 = 2.5758293035489004
631631
ax.axhline(y=z99 / np.sqrt(n), linestyle='--', color='grey')

pandas/plotting/_style.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import numpy as np
66

7-
from pandas.compat import lmap, lrange
7+
from pandas.compat import lrange
88

99
from pandas.core.dtypes.common import is_list_like
1010

@@ -20,7 +20,7 @@ def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
2020
colormap = cm.get_cmap(colormap)
2121
if colormap is None:
2222
raise ValueError("Colormap {0} is not recognized".format(cmap))
23-
colors = lmap(colormap, np.linspace(0, 1, num=num_colors))
23+
colors = [colormap(num) for num in np.linspace(0, 1, num=num_colors)]
2424
elif color is not None:
2525
if colormap is not None:
2626
warnings.warn("'color' and 'colormap' cannot be used "
@@ -49,7 +49,7 @@ def random_color(column):
4949
rs = com.random_state(column)
5050
return rs.rand(3).tolist()
5151

52-
colors = lmap(random_color, lrange(num_colors))
52+
colors = [random_color(num) for num in lrange(num_colors)]
5353
else:
5454
raise ValueError("color_type must be either 'default' or 'random'")
5555

pandas/tests/frame/test_constructors.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy.ma as ma
88
import pytest
99

10-
from pandas.compat import PY36, is_platform_little_endian, lmap
10+
from pandas.compat import PY36, is_platform_little_endian
1111

1212
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
1313
from pandas.core.dtypes.common import is_integer_dtype
@@ -2224,7 +2224,7 @@ def __iter__(self):
22242224
return iter(self.args)
22252225

22262226
recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)]
2227-
tups = lmap(tuple, recs)
2227+
tups = [tuple(rec) for rec in recs]
22282228

22292229
result = DataFrame.from_records(recs)
22302230
expected = DataFrame.from_records(tups)

pandas/tests/frame/test_to_csv.py

+28-18
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import numpy as np
66
import pytest
77

8-
from pandas.compat import lmap
98
from pandas.errors import ParserError
109

1110
import pandas as pd
@@ -120,8 +119,8 @@ def test_to_csv_from_csv3(self):
120119
df2.to_csv(path, mode='a', header=False)
121120
xp = pd.concat([df1, df2])
122121
rs = pd.read_csv(path, index_col=0)
123-
rs.columns = lmap(int, rs.columns)
124-
xp.columns = lmap(int, xp.columns)
122+
rs.columns = [int(label) for label in rs.columns]
123+
xp.columns = [int(label) for label in xp.columns]
125124
assert_frame_equal(xp, rs)
126125

127126
def test_to_csv_from_csv4(self):
@@ -292,19 +291,24 @@ def _to_uni(x):
292291
if r_dtype:
293292
if r_dtype == 'u': # unicode
294293
r_dtype = 'O'
295-
recons.index = np.array(lmap(_to_uni, recons.index),
296-
dtype=r_dtype)
297-
df.index = np.array(lmap(_to_uni, df.index), dtype=r_dtype)
294+
recons.index = np.array(
295+
[_to_uni(label) for label in recons.index],
296+
dtype=r_dtype)
297+
df.index = np.array(
298+
[_to_uni(label) for label in df.index], dtype=r_dtype)
298299
elif r_dtype == 'dt': # unicode
299300
r_dtype = 'O'
300-
recons.index = np.array(lmap(Timestamp, recons.index),
301-
dtype=r_dtype)
301+
recons.index = np.array(
302+
[Timestamp(label) for label in recons.index],
303+
dtype=r_dtype)
302304
df.index = np.array(
303-
lmap(Timestamp, df.index), dtype=r_dtype)
305+
[Timestamp(label) for label in df.index],
306+
dtype=r_dtype)
304307
elif r_dtype == 'p':
305308
r_dtype = 'O'
309+
idx_list = to_datetime(recons.index)
306310
recons.index = np.array(
307-
list(map(Timestamp, to_datetime(recons.index))),
311+
[Timestamp(label) for label in idx_list],
308312
dtype=r_dtype)
309313
df.index = np.array(
310314
list(map(Timestamp, df.index.to_timestamp())),
@@ -316,23 +320,29 @@ def _to_uni(x):
316320
if c_dtype:
317321
if c_dtype == 'u':
318322
c_dtype = 'O'
319-
recons.columns = np.array(lmap(_to_uni, recons.columns),
320-
dtype=c_dtype)
323+
recons.columns = np.array(
324+
[_to_uni(label) for label in recons.columns],
325+
dtype=c_dtype)
321326
df.columns = np.array(
322-
lmap(_to_uni, df.columns), dtype=c_dtype)
327+
[_to_uni(label) for label in df.columns],
328+
dtype=c_dtype)
323329
elif c_dtype == 'dt':
324330
c_dtype = 'O'
325-
recons.columns = np.array(lmap(Timestamp, recons.columns),
326-
dtype=c_dtype)
331+
recons.columns = np.array(
332+
[Timestamp(label) for label in recons.columns],
333+
dtype=c_dtype)
327334
df.columns = np.array(
328-
lmap(Timestamp, df.columns), dtype=c_dtype)
335+
[Timestamp(label) for label in df.columns],
336+
dtype=c_dtype)
329337
elif c_dtype == 'p':
330338
c_dtype = 'O'
339+
col_list = to_datetime(recons.columns)
331340
recons.columns = np.array(
332-
lmap(Timestamp, to_datetime(recons.columns)),
341+
[Timestamp(label) for label in col_list],
333342
dtype=c_dtype)
343+
col_list = df.columns.to_timestamp()
334344
df.columns = np.array(
335-
lmap(Timestamp, df.columns.to_timestamp()),
345+
[Timestamp(label) for label in col_list],
336346
dtype=c_dtype)
337347
else:
338348
c_dtype = type_map.get(c_dtype)

pandas/tests/groupby/test_groupby.py

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

9-
from pandas.compat import lmap
109
from pandas.errors import PerformanceWarning
1110

1211
import pandas as pd
@@ -874,7 +873,7 @@ def test_mutate_groups():
874873
'cat1': ['a'] * 8 + ['b'] * 6,
875874
'cat2': ['c'] * 2 + ['d'] * 2 + ['e'] * 2 + ['f'] * 2 + ['c'] * 2 +
876875
['d'] * 2 + ['e'] * 2,
877-
'cat3': lmap(lambda x: 'g%s' % x, range(1, 15)),
876+
'cat3': ['g{}'.format(x) for x in range(1, 15)],
878877
'val': np.random.randint(100, size=14),
879878
})
880879

@@ -1248,17 +1247,17 @@ def test_groupby_sort_multi():
12481247
'c': [0, 1, 2],
12491248
'd': np.random.randn(3)})
12501249

1251-
tups = lmap(tuple, df[['a', 'b', 'c']].values)
1250+
tups = [tuple(row) for row in df[['a', 'b', 'c']].values]
12521251
tups = com.asarray_tuplesafe(tups)
12531252
result = df.groupby(['a', 'b', 'c'], sort=True).sum()
12541253
tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]])
12551254

1256-
tups = lmap(tuple, df[['c', 'a', 'b']].values)
1255+
tups = [tuple(row) for row in df[['c', 'a', 'b']].values]
12571256
tups = com.asarray_tuplesafe(tups)
12581257
result = df.groupby(['c', 'a', 'b'], sort=True).sum()
12591258
tm.assert_numpy_array_equal(result.index.values, tups)
12601259

1261-
tups = lmap(tuple, df[['b', 'c', 'a']].values)
1260+
tups = [tuple(x) for x in df[['b', 'c', 'a']].values]
12621261
tups = com.asarray_tuplesafe(tups)
12631262
result = df.groupby(['b', 'c', 'a'], sort=True).sum()
12641263
tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]])
@@ -1270,7 +1269,7 @@ def test_groupby_sort_multi():
12701269
result = grouped.sum()
12711270

12721271
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
1273-
tups = lmap(tuple, df[keys].values)
1272+
tups = [tuple(row) for row in df[keys].values]
12741273
tups = com.asarray_tuplesafe(tups)
12751274
expected = f(df.groupby(tups)[field])
12761275
for k, v in expected.items():

pandas/tests/indexes/datetimes/test_tools.py

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

1515
from pandas._libs import tslib
1616
from pandas._libs.tslibs import iNaT, parsing
17-
from pandas.compat import lmap
1817
from pandas.errors import OutOfBoundsDatetime
1918
import pandas.util._test_decorators as td
2019

@@ -1264,7 +1263,7 @@ def test_to_datetime_types(self, cache):
12641263
# array = ['2012','20120101','20120101 12:01:01']
12651264
array = ['20120101', '20120101 12:01:01']
12661265
expected = list(to_datetime(array, cache=cache))
1267-
result = lmap(Timestamp, array)
1266+
result = [Timestamp(date_str) for date_str in array]
12681267
tm.assert_almost_equal(result, expected)
12691268

12701269
# currently fails ###

0 commit comments

Comments
 (0)