1

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?

1
  • The idea of lambda is that it is anonymous so you don't need to assign it to a variable. Commented Aug 30, 2017 at 12:39

3 Answers 3

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

The speed difference is even larger in my computer: 82.6ms for np.core.char.add while 163ms for list(map(...)).
4

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.