2

I have two arrays, and want to combine the ith elements in each one together:

import numpy as np
a = np.array(['a', 'b', 'c'])
b = np.array(['x', 'y', 'z'])

I want to return

array(['ax', 'by', 'cz'])

What is the function for this? Thx,

1 Answer 1

7
>>> import numpy as np
>>> a = np.array(['a', 'b', 'c'])
>>> b = np.array(['x', 'y', 'z'])
>>> c = np.array([i+j for i, j in zip(a, b)])
>>> c
array(['ax', 'by', 'cz'],
      dtype='|S2')

@DSM makes the point that if a and b had dtype=object you could simply add the two arrays together:

>>> a = np.array(["a", "b", "c"], dtype=object)
>>> b = np.array(["x", "y", "z"], dtype=object)
>>> c = a + b
>>> c
array([ax, by, cz], dtype=object)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I knew it was simple, just couldn't nail it down.
@mike no problem, when combining iterables it's almost always worth trying zip.
If a and b had dtype=object, then a+b would Just Work(tm). [Actually, I think either one would suffice.]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.