在python中将数组附加到其他数组的每个元素上



我有这样一个数组:

a = np.array(([11,12,13],[21,22,23],[31,32,33],[41,42,43]))
b = np.array([88,99])

我想要得到:

c = np.array(([11,12,13,88,99],[21,22,23,88,99],[31,32,33,88,99],[41,42,43,88,99]))

我该怎么做呢?由于

假设您有numpy数组,您可以这样做:

import numpy as np
np.concatenate([a, np.tile(b, (len(a), 1))], 1)

或者,使用numpy.broadcast_to:

np.concatenate([a, np.broadcast_to(b, (len(a), len(b)))], 1)

输出:

array([[11, 12, 13, 88, 99],
[21, 22, 23, 88, 99],
[31, 32, 33, 88, 99],
[41, 42, 43, 88, 99]])

带列表的解:

a_list = a.tolist()
b_list = b.tolist()
from itertools import product, chain
[list(chain(*i)) for i in product(a_list, [b_list])]

输出:

[[11, 12, 13, 88, 99],
[21, 22, 23, 88, 99],
[31, 32, 33, 88, 99],
[41, 42, 43, 88, 99]]

可以使用NumPy追加

import numpy as np
a = np.array(([11,12,13],[21,22,23],[31,32,33],[41,42,43]))
b = np.array([88,99])
c= np.array([np.append(arr, b) for arr in a  ])

输出:

array([[11, 12, 13, 88, 99],
[21, 22, 23, 88, 99],
[31, 32, 33, 88, 99],
[41, 42, 43, 88, 99]])

相关内容

  • 没有找到相关文章

最新更新