如何合并2个numpy数组并连接它们的值?

时间:2016-04-18 17:48:02

标签: python arrays numpy optimization

有没有办法从这个Python-arrays合并中获得相同的结果:

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]

但直接在 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])

我的第一个(也是显而易见的)解决方案是:

c = np.array([int(''.join (map(str, xs))) for xs in zip(a.tolist(),b.tolist())])

c
Out[12]: array([14, 23, 32, 41])

但是我想知道是否有可能直接使用numpy-arrays,而不将它们转换为python-arrays。

注意:我使用1,2,3,4值进行简化,我希望在两个大小>的数组上都有一个+两位数的解决方案。 10 ** 4。

更新了不同解决方案的时间:

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

验证结果:

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

3 个答案:

答案 0 :(得分:4)

您可以使用dtype参数让您的numpy数组成为string数组,您可以在add上使用自由函数numpy.char将它们连接起来 - 如此,

a = numpy.array([1,2,3,4], dtype=numpy.str)
b = numpy.array([4,3,2,1], dtype=numpy.str)

c = numpy.char.add(a, b).astype(int)

<强>输出

[14 23 32 41]

答案 1 :(得分:1)

我用一段解决方案编写了一个函数,我想了一会儿后发现:

def merge(a,b):
#: I don't find a better way to create this array
nines = np.array([9,99,999,9999,99999,999999,9999999, 99999999])

#: get number of digits
exp = np.log10(a)+1

#: fix the zeros
exp[exp == -np.inf] = 1

#: fix the nines
exp[np.in1d(a,nines)] += 1

c = a * 10**exp.astype(int) + b
return c

看起来似乎太过于过度思考,但它比其他解决方案更快 (x10):

%%timeit
c = merge(a,b)
10 loops, best of 3: 128 ms per loop

答案 2 :(得分:1)

这是一种使用NumPy数学函数的方法 -

a*(10**(np.log10(b).astype(int)+1)) + b

示例运行 -

In [32]: a
Out[32]: array([ 16,   2, 399,   4])

In [33]: b
Out[33]: array([  4,  38,   2, 190])

In [34]: a*(10**(np.log10(b).astype(int)+1)) + b
Out[34]: array([ 164,  238, 3992, 4190])