Is there a way to obtain the same result from this Python-arrays merge:
a = [1,2,3,4]
b = [4,3,2,1]
c = [ int(''.join (map (str, xs))) for xs in zip (a,b) ]
c
Out[4]: [14, 23, 32, 41]
But operating directly on Numpy-arrays:
a
Out[9]: array([1, 2, 3, 4])
b
Out[10]: array([4, 3, 2, 1])
c = Your Answer
c
# desired output: array([14, 23, 32, 41])
My first (and obvious) solution was:
c = np.array([int(''.join (map(str, xs))) for xs in zip(a.tolist(),b.tolist())])
c
Out[12]: array([14, 23, 32, 41])
But I would like to know if it's possible to do that directly with the numpy-arrays, without converting them to python-arrays.
Note: I use 1,2,3,4 values for simplification, I would like to have a solution that work with +double digits on both arrays of size > 10**4.
Updated with timings for different solutions:
a = np.arange(1000000)
b = np.arange(1,1000001)
#: Mi first Solution
%%timeit
c = np.array([int(''.join (map(str, xs))) for xs in zip(a.tolist(),b.tolist())])
1 loop, best of 3: 1.99 s per loop
#: Donkey's Solution (thought to smaller arrays)
%%timeit
c = np.char.add(a.astype(str),b.astype(str)).astype(int)
1 loop, best of 3: 1.8 s per loop
#: My second Solution
%%timeit
c = merge(a,b)
10 loops, best of 3: 128 ms per loop
#: Divakar's Solution
%%timeit
c = a*(10**(np.log10(b).astype(int)+1)) + b
10 loops, best of 3: 117 ms per loop
Verify results:
c1 = np.array([int(''.join (map(str, xs))) for xs in zip(a.tolist(),b.tolist())])
c2 = np.char.add(a.astype(str),b.astype(str)).astype(int)
c3 = merge(a,b)
np.alltrue(np.logical_and(c1==c2,c2==c3))
Out[51]: True
c4 = a*(10**(np.log10(b).astype(int)+1)) + b
np.alltrue(np.logical_and(c1==c2,c2==c4))
Out[58]: True
c = 10*a + b