Concatenating string arrays
![](https://secure.gravatar.com/avatar/f586e2a9879fe0a55fd1e3ea529c664f.jpg?s=120&d=mm&r=g)
Hello, I am trying to find an efficient way to concatenate the elements of two same-length numpy str arrays. For example if I define the following arrays: import numpy as np arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f']) I would like to produce a third array that would contain ['ad','be','cf']. Is there an efficient way to do this? I could do this element by element, but I need a faster method, as I need to do this on arrays with several million elements. Thanks for any help, Thomas
![](https://secure.gravatar.com/avatar/86ea939a72cee216b3c076b52f48f338.jpg?s=120&d=mm&r=g)
On 3/18/2009 7:30 PM, Thomas Robitaille wrote:
import numpy as np arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f'])
I would like to produce a third array that would contain ['ad','be','cf']. Is there an efficient way to do this? I could do this element by element, but I need a faster method, as I need to do this on arrays with several million elements.
arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f']) arr3 = np.zeros(6, dtype='|S1') arr3[::2] = arr1 arr3[1::2] = arr2 arr3.view(dtype='|S2') array(['ad', 'be', 'cf'], dtype='|S2')
Does this help? Sturla Molden
![](https://secure.gravatar.com/avatar/bd813aa01a8be59c71e6c797194beffe.jpg?s=120&d=mm&r=g)
A Wednesday 18 March 2009, Sturla Molden escrigué:
On 3/18/2009 7:30 PM, Thomas Robitaille wrote:
import numpy as np arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f'])
I would like to produce a third array that would contain ['ad','be','cf']. Is there an efficient way to do this? I could do this element by element, but I need a faster method, as I need to do this on arrays with several million elements.
arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f']) arr3 = np.zeros(6, dtype='|S1') arr3[::2] = arr1 arr3[1::2] = arr2 arr3.view(dtype='|S2')
array(['ad', 'be', 'cf'], dtype='|S2')
Nice example. After looking at this, it is apparent how beneficial can be the mutable types provided by NumPy. -- Francesc Alted
![](https://secure.gravatar.com/avatar/f586e2a9879fe0a55fd1e3ea529c664f.jpg?s=120&d=mm&r=g)
import numpy as np arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f'])
I would like to produce a third array that would contain ['ad','be','cf']. Is there an efficient way to do this? I could do this element by element, but I need a faster method, as I need to do this on arrays with several million elements.
arr1 = np.array(['a','b','c']) arr2 = np.array(['d','e','f']) arr3 = np.zeros(6, dtype='|S1') arr3[::2] = arr1 arr3[1::2] = arr2 arr3.view(dtype='|S2') array(['ad', 'be', 'cf'], dtype='|S2')
Does this help?
This works wonderfully - thanks! Tom
participants (3)
-
Francesc Alted
-
Sturla Molden
-
Thomas Robitaille