0

The following code works well in python2, but after migration to python3, it does not work. How do I change this code in python3?

for i, idx in enumerate(indices):
    user_id, item_id = idx 
    feature_seq = np.array(map(lambda x: user_id, item_id))  
    X[i, :len(item_id), :] = feature_seq  # ---- error here ---- 

error:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'map'

Thank you.

MegaIng
  • 7,361
  • 1
  • 22
  • 35
Chris Joo
  • 577
  • 10
  • 24
  • In PY3, `map` is like a generator, you need to wrap it in `list()` to produce a list that `np.array` can use: e.g. `np.array(list(map(...)))`. – hpaulj Jun 13 '17 at 03:20
  • Thank you sooooooooooo much!! – Chris Joo Jun 13 '17 at 03:23
  • 1
    Possible duplicate of [Convert map object to numpy array in python 3](https://stackoverflow.com/questions/28524378/convert-map-object-to-numpy-array-in-python-3) – Georgy May 11 '18 at 09:52

2 Answers2

5

In python3, Map returns a iterator, not a list. You can also try numpy.fromiter to get an array from a map obj,only for 1-D data.

Example:

a=map(lambda x:x,range(10))
b=np.fromiter(a,dtype=np.int)
b

Ouput:

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

For multidimensional arrays, refer to Reconcile np.fromiter and multidimensional arrays in Python

Jay
  • 738
  • 8
  • 14
4

In PY3, map is like a generator. You need to wrap it in list() to produce a list that np.array can use: e.g.

 np.array(list(map(...)))
hpaulj
  • 221,503
  • 14
  • 230
  • 353