Skip to main content
 首页 » 编程设计

python之numpy 将数组附加到数组

2025年05月04日15tuyile006

我正在尝试将一个 numpy 数组附加到另​​一个 numpy 数组,如下所示:

import numpy as np 
meanings = 2 
signals = 4 
 
def new_agent(agent_type, context_size): 
    if agent_type == 'random': 
        comm_system = np.random.random_integers(0, 1, (meanings, signals)) 
    if agent_type == 'blank': 
        comm_system = np.zeros((meanings, signals), int) 
    score_list = np.array([0., 0., 0., 0.]) 
    np.append(comm_system, score_list) 
    np.append(comm_system, context_size) 
    return comm_system 

如果我现在调用:

random_agent = new_agent('random', 5) 

我希望得到类似的东西:

[[0 1 0 0] 
[1 1 0 1] 
[0. 0. 0. 0.] 
5] 

但我只得到:

[[0 1 0 0] 
[1 1 0 1]] 

因此不会附加 score_list 和 context_size。当我用“空白”调用 new_agent() 时也是如此。

谢谢!

请您参考如下方法:

您可以使用hstack 和vstack 来连接数组:

>>> from numpy import array, hstack, vstack 
>>> a = array([1, 2, 3]) 
>>> b = array([4, 5, 6]) 
 
>>> hstack([a, b]) 
array([1, 2, 3, 4, 5, 6]) 
 
>>> vstack([a, b]) 
array([[1, 2, 3], 
       [4, 5, 6]])