在python中

时间:2018-08-10 20:13:30

标签: python arrays numpy

大家好,我想在python中并排添加2个2x2数组。最后,我想获得一个2x4数组,该行共享行,第1列和第2列来自第一个数组,第3列和第4列来自第二个数组。我得到一个数组,它求和的数组不并排放置。你能帮我吗?

示例:

Array 1:
[[1 2]
 [1 2]]

Array 2:
[[1 2]
 [1 2]]

预期结果:

[[1 2 1 2]
 [1 2 1 2]]

实际结果:

[[2 4]
 [2 4]]

import numpy as np

a = np.matrix('1 2; 1 2')
b = np.matrix('1 2; 1 2')

x = a + b

print(x)

3 个答案:

答案 0 :(得分:4)

使用np.concatenate

>>> numpy.concatenate((a, b), axis=1)
matrix([[1, 2, 1, 2],
       [1, 2, 1, 2]])

另一个选择是使用np.hstack

>>> np.hstack((a, b))
matrix([[1, 2, 1, 2],
        [1, 2, 1, 2]])

答案 1 :(得分:2)

<pre> 4. a. Text goes here and when it word wraps it needs to keep the indent with the text like so b. This is a separate field, with its own caption but needs the same indentation as above 5. Another separate caption, but this line does not have sub sections </pre> <div id="container"> <ol start="4"> <li> <ol> <li>Text goes here and when it word wraps it needs to keep the indent with the text like so</li> </ol> </li> </ol> <ol start="4" class="empty"> <li> <ol start="2"> <li>This is a separate field, with its own caption but needs the same indentation as above</li> </ol> </li> </ol> <ol start="5"> <li class="no-sub">Another separate caption, but this line does not have sub sections</li> </ol> </div>数组的作用方式与python列表不同。 body { background: url(../images/background.jpg); background-repeat: no-repeat; background-position: 0px 0px; background-attachment: fixed; background-color: #fff; -webkit-background-size: calc(100vw) calc(100vh); -moz-background-size: calc(100vw) calc(100vh); -o-background-size: calc(100vw) calc(100vh); background-size: calc(100vw) calc(100vh); } 运算符可以执行某种列表串联操作,而将其与numpy数组一起使用时,则在执行矢量加法运算。

相反,您可以展平每个数组并进行串联:

+

[编辑:]

重新阅读您的问题,似乎我误解了您所追求的。 @Thomas的答案在您的情况中更有意义,可以选择使用np.column_stack

numpy

答案 2 :(得分:1)

我之所以会这样,是因为加法返回了一个正常的矩阵加法,该法将两个矩阵逐个相加。

尝试使用np.concatenate(),它可能会如@sacul的建议那样有所帮助。