简体   繁体   English

如何合并两个numpy数组的数字

[英]How to combine the digits of two numpy arrays

Strange question, I can concat two digits by int(str(2)+str(3)) but how to this for two numpy arrays? 奇怪的问题,我可以用int(str(2)+str(3))合并两位数,但是对于两个numpy数组该如何处理呢? Like 喜欢

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[4,5,6],[1,2,3]])
z = np.xx(x,y)
print(z)

array([[14, 25, 36],
       [41, 52, 63]])

Here is a pure numpy solution, which does not involve any mappings to other datastructures. 这是一个纯粹的numpy解决方案,它不涉及到其他数据结构的任何映射。 It should be far faster than the list comprehension, especially for large matrices. 它应该比列表理解要快得多,尤其是对于大型矩阵。

import numpy as np

x = np.array([[10,2,3],[4,5,6]])
y = np.array([[4,5,6],[1,2,3]])

digits = np.log10(y).astype(np.int)+1

z = x*(10**digits)+y
print z

I changed the 1 to a 10 to show it works for multiple digits; 我将1更改为10,以显示它适用于多个数字; but if your numbers are always in the range 0-9, as in your example, you can of course completely do away with the digit logic. 但是,如您的示例所示,如果您的数字始终在0-9范围内,那么您当然可以完全取消数字逻辑。

You can use zip and a list comprehension: 您可以使用zip和列表理解:

In [7]: np.array([[str(c) + str(d) for c, d in zip(a, b)] for a, b in zip(x, y)],
                                                                          dtype=int)     
Out[7]: 
array([[14, 25, 36],                                                                             
       [41, 52, 63]])    

or: 要么:

In [20]: np.array([str(a)+str(b) for a, b in zip(*np.hstack((x, y)))],
                                                        dtype=int).reshape(x.shape)                                                                                                
Out[20]: 
array([[14, 25, 36],                                                                             
       [41, 52, 63]])     

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

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