首页 > 解决方案 > 如何扩展numpy数组

问题描述

我有 2 个 numpy 数组,我想使用扩展将这两个数组组合在一起。例如:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[0,0,0],[1,1,1]]

我想要的是 c = [[1,2,3],[4,5,6],[7,8,9],[0,0,0],[1,1,1]]

看来我不能extend用作 python 列表。否则会引发AttributeError: 'numpy.ndarray' object has no attribute 'extend'错误。

目前我尝试将它们转换为列表:

a_list = a.tolist()
b_list = b.tolist()
a_list.extend(b_list)
c = numpy.array(a_list)

我想知道是否存在更好的解决方案?

标签: pythonnumpy

解决方案


利用 -

np.concatenate((a, b), axis=0)

或者 -

np.vstack((a,b))

或者 -

a.append(b) # appends in-place, a will get modified directly

输出

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [0, 0, 0],
       [1, 1, 1]])

推荐阅读