如何在2D数组的每一行中添加数组?

时间:2019-04-11 14:31:11

标签: python arrays numpy

我想对两个数组进行元素加法。第一个是1D,包含在键“ cras”下的字典中,第二个是2D。示例:

   OrderedDict([('head', array([ 2,  0, 20], dtype=int32)), ('valid', '1  # 
   volume info valid'), ('filename', '../mri/filled-pretess255.mgz'), 
   ('volume', array([256, 256, 256])), ('voxelsize', array([1., 1., 1.])), 
   ('xras', array([-1.,  0.,  0.])), ('yras', array([ 0.,  0., -1.])), 
    ('zras', array([0., 1., 0.])), ('cras', array([-3.433, 18.419, 28.598]))])

    'cras', array([-3.433, 18.419, 28.598])

添加到

的每个元素
[[ -9.022 -81.936  -1.822]
 [ -9.554 -82.001  -1.929]
 [-10.186 -81.872  -1.779]
 ...
 [-16.673  76.043 -18.319]
 [-16.989  76.213 -17.823]
 [-17.568  75.554 -18.709]]

预期结果:

[-3.433+(-9.022), 18.419+(-81.936), 28.598+(-1.822)]
....

如何实现?

2 个答案:

答案 0 :(得分:1)

如果数据非常大,则可能需要研究numpy模块。如果没有,则可以使用zip和列表理解功能来实现:

matrix = [[ -9.022, -81.936,  -1.822],
          [ -9.554, -82.001,  -1.929],
          [-10.186, -81.872,  -1.779],
          [-16.673,  76.043, -18.319],
          [-16.989,  76.213, -17.823],
          [-17.568,  75.554, -18.709]]

cras   = [-3.433, 18.419, 28.598]

result = [ [ a+b for a,b in zip(cras,line) ] for line in matrix ]

for line in result: print(line)

# (rounded and aligned the printed values for legibility)
[-12.455, -63.517, 26.776]
[-12.987, -63.582, 26.669]
[-13.619, -63.453, 26.819]
[-20.106,  94.462, 10.279]
[-20.422,  94.632, 10.775]
[-21.001,  93.973,  9.889]

答案 1 :(得分:0)

您正在尝试添加

的内容
  

cras

如果我正确理解的话,请

查看您提供的示例2D列表的每个元素。我所做的是将您的样本列表转换为numpy数组,然后再次使用numpy执行逐元素加法。

from collections import OrderedDict
from numpy import array, int32, asarray, add

def adding():
    dict = OrderedDict([('head', array([2, 0, 20], dtype=int32)), ('valid', '1  # \
                 volume info valid'), ('filename', '.. / mri / filled - pretess255.mgz'),
                 ('volume', array([256, 256, 256])), ('voxelsize', array([1., 1., 1.])),
                 ('xras', array([-1., 0., 0.])), ('yras', array([0., 0., -1.])),
                 ('zras', array([0., 1., 0.])), ('cras', array([-3.433, 18.419, 28.598]))])

    'cras', array([-3.433, 18.419, 28.598])

    sample_arr = asarray([[-9.022, -81.936, -1.822],
                 [-9.554, -82.001, -1.929],
                 [-10.186, -81.872, -1.779],
                 [-16.673,  76.043, -18.319],
                 [-16.989, 76.213, -17.823],
                 [-17.568,  75.554, -18.709]])

    result = add(dict['cras'], sample_arr)
    print(result)
    print([-3.433+(-9.022), 18.419+(-81.936), 28.598+(-1.822)])

结果:

[[-12.455 -63.517  26.776]
 [-12.987 -63.582  26.669]
 [-13.619 -63.453  26.819]
 [-20.106  94.462  10.279]
 [-20.422  94.632  10.775]
 [-21.001  93.973   9.889]]

[-12.455, -63.51700000000001, 26.776]