0

I need this functionality, but by using numpy arrays instead of python lists

my_list = ['f', 'o', 'o', 'b', 'a', 'r']
new_list = list()    
for elem in my_list:
    new_list.append(func(elem))

for loop consumes lot of time and cpu if the list becomes large. So I need this functionality with numpy array. Help out!

  • 2
    Does this answer your question? [Most efficient way to map function over numpy array](https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array) – ThePyGuy Aug 20 '21 at 19:19
  • 1
    As long as `func` has to be applied once to every element of the list, there isn't a `numpy` way of improving on this. Iteration on a list is faster than on an array. `numpy` code is fast, if you start with arrays, and apply the compiled whole-array methods. – hpaulj Aug 20 '21 at 20:35
  • 1
    You don't tell us anything about `func`, but `my_list` contains strings/characters. `numpy` does not have any fast compiled methods for strings. The fast stuff is for numbers. String dtype is ok for basic array operations like reshape, but for work on individual elements it depends on Python string methods. – hpaulj Aug 20 '21 at 21:28

2 Answers2

0

You can use map

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

np.array(list(map(func, my_list)))
Joyescat
  • 507
  • 5
  • 11
  • 1
    In my experience `map` and list comprehensions run about the same. And only modestly faster than the OP's for/append. – hpaulj Aug 20 '21 at 20:37
0

For convenience, you can vectorize func to make it more elegant, and remove this for-loop.

import numpy as np

def func(v):
    return v ** 2

my_list = [1, 2, 3, 4]
vfunc = np.vectorize(func)
array = vfunc(my_list)

The above results with this:

array([1, 4, 9, 16])
ronpi
  • 470
  • 3
  • 8
  • 2
    That's for convenience, not speed. And as many SO questions show, using `np.vectorize` has pitfalls. – hpaulj Aug 20 '21 at 20:33