0

I have a 2D numpy array as shown below

[['me' 'you']
 ['her' 'him']]

I want to get a numpy array like this

['meyou'
'herhim']

which should be a 1D numpy array

How do I do it in the most efficient way in terms of speed?

1
  • How ever you do it, it's a python string operation. Even with np.char. So there's no superfast array approach. Commented Aug 11, 2018 at 0:13

2 Answers 2

1

Simply "add" the two columns using NumPy's string manipulation:

 np.char.add(x[:,0], x[:,1])

Or more generally, for any number of columns, here is a simple solution (if the number of columns is large, this is not efficient):

from functools import reduce # not needed in Python 2
reduce(np.char.add, x.T)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a list comprehension, whereby you join all the values within the same sublist together:

["".join(i) for i in x]

['meyou', 'herhim']

1 Comment

Even if you take into account casting this back into a numpy array it's faster than using numpy methods

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.