繁体   English   中英

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

[英]How to merge 2 numpy arrays and concatenate their values?

有没有办法从此Python数组合并中获得相同的结果:

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

您可以使用dtype参数使numpy数组成为string数组,您可以在其上简单地使用free函数add in 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]

经过一段时间的思考,我编写了一个带有解决方案的函数:

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

这是一种使用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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM