如何连接二维numpy字符串数组的相同位置元素?

时间:2018-10-17 06:56:13

标签: python numpy

我有以下代码:

a = np.arange(25).reshape(5,5)
b = np.arange(25).reshape(5,5)
c = a.astype( str )
d = b.astype( str )

矩阵a和b为:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

矩阵c和d为:

array([['0', '1', '2', '3', '4'],
       ['5', '6', '7', '8', '9'],
       ['10', '11', '12', '13', '14'],
       ['15', '16', '17', '18', '19'],
       ['20', '21', '22', '23', '24']], dtype='|S11')

我想通过使用c和d操作获得以下矩阵。

array([['00', '11', '22', '33', '44'],
       ['55', '66', '77', '88', '99'],
       ['1010', '1110', '1212', '1313', '1414'],
       ['1515', '1616', '1717', '1818', '1919'],
       ['2020', '2121', '2222', '2323', '2424']], dtype='|S11')

怎么办?

1 个答案:

答案 0 :(得分:1)

为什么不

>>> np.core.defchararray.add(a.astype(str), b.astype(str))
array([['00', '11', '22', '33', '44'],
       ['55', '66', '77', '88', '99'],
       ['1010', '1111', '1212', '1313', '1414'],
       ['1515', '1616', '1717', '1818', '1919'],
       ['2020', '2121', '2222', '2323', '2424']], dtype='<U22')


可重复性材料

import numpy as np
a = np.array(
    [[ 0,  1,  2,  3,  4],
     [ 5,  6,  7,  8,  9],
     [10, 11, 12, 13, 14],
     [15, 16, 17, 18, 19],
     [20, 21, 22, 23, 24]]
)
b = np.array(
    [['0', '1', '2', '3', '4'],
     ['5', '6', '7', '8', '9'],
     ['10', '11', '12', '13', '14'],
     ['15', '16', '17', '18', '19'],
     ['20', '21', '22', '23', '24']],
    dtype='|S11'
)