Digvijay Sawant
Digvijay Sawant

Reputation: 1079

iterating over numpy array using lambda

I have a numpy array of numbers like this:cols = np.arange(1, 6). I want to append the letter 't' in front of every number in cols. I write the followind loc:

f = lambda x: 't' + str(x)
temp = f(cols)
print(temp)

I get an output like this:

t[1 2 3 4 5].

I need the output to be ['t1', 't2', 't3'...]. I need to do it for 1000s of numbers. What am I doing wrong?

Upvotes: 1

Views: 3835

Answers (3)

akuiper
akuiper

Reputation: 214967

You can use np.core.char.add:

np.core.char.add('t', np.arange(1,6).astype(str))
#array(['t1', 't2', 't3', 't4', 't5'], 
#      dtype='|S12')

It's faster then list(map(...)) for large arrays:

%timeit np.core.char.add('t', np.arange(1,100000).astype(str))
# 10 loops, best of 3: 31.7 ms per loop

f = lambda x: 't' + str(x)
%timeit list(map(f, np.arange(1,100000).astype(str)))
# 10 loops, best of 3: 38.8 ms per loop

Upvotes: 9

Chen A.
Chen A.

Reputation: 11280

You can to do that with list comprehension:

['t' + str(x) for x in cols]
['t1', 't2', 't3', 't4', 't5', 't6']

This will append 't' for every element x in collection cols.

lambda function is an anonymous function, so you usually pass it into functions that expects a callable object.

Upvotes: 4

Chris
Chris

Reputation: 22953

Your problem is that your applying your function to the entire array. Your basically doing:

't' + str(cols)

Which of course does not work. You need to apply it element-wise:

list(map(f, cols)) # No need for list() if using Python 2

Upvotes: 2

Related Questions