2013-11-20 155 views
1

我想一個numpy的數組追加到另一個數組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()時也是如此。

謝謝!

回答

2

numpy.append()返回包含來自其輸入的數據的新數組。它不會自行修改輸入,並且它不可能這樣做。這是因爲NumPy中的數組通常不能調整大小。

嘗試更改您的代碼以捕獲從append()返回的值,該值將是您想要的數組。

1

@John是正確的關於如何使用返回值從numpy.append,因爲它不會修改原始數組。然而,有一個與你的預期輸出的一個問題:

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

是不是因爲兩個原因,一個可能的numpy的數組:一個是一些元素是整數的,有些是浮動的,但一個numpy的陣列的D型必須是統一的;另一個是每行不是相同的長度,但numpy數組必須具有統一的(矩形)形狀。

我想你可能寧願做的是剛剛返回所有的三件事情:

  • comm_system爲int數組,
  • score_list爲float數組,
  • context_size爲int (不是數組)。

你可以做到這一點與一個元組:

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.zeros(signals) #This is different too! No need to type out the 0, 0, ... 
    # now just return all three: 
    return comm_system, score_list, context_size 

然後你就可以 「解壓」 的元組,像這樣:

random_agent, scores, size = new_agent('random', 5) 

或者只是讓他們都在同一個元組:

random_agent_info = new_agent('random', 5) 

而且你將有

In [331]: random_agent, scores, size = new_agent('random', 5) 

In [332]: random_agent 
Out[332]: 
array([[0, 1, 1, 0], 
     [0, 1, 0, 1]]) 

In [333]: scores 
Out[333]: array([ 0., 0., 0., 0.]) 

In [334]: size 
Out[334]: 5 

In [336]: random_agent_info 
Out[336]: 
(array([[1, 1, 0, 1], 
     [0, 1, 0, 0]]), 
array([ 0., 0., 0., 0.]), 
5) 

In [337]: random_agent_info[0] 
Out[337]: 
array([[1, 1, 0, 1], 
     [0, 1, 0, 0]]) 

In [338]: random_agent_info[1] 
Out[338]: array([ 0., 0., 0., 0.]) 

In [339]: random_agent_info[2] 
Out[339]: 5 

如果你想有comm_systemscore_list是一個(3,2)數組,你可以做到這一點:

def new_agent(agent_type, context_size): 
    ... 
    return np.vstack([comm_system, score_list]), context_size 

然後你會得到一個陣列和一個INT:

In [341]: random_agent, size = new_agent('random', 5) 

In [342]: random_agent 
Out[342]: 
array([[ 1., 0., 1., 1.], 
     [ 1., 0., 1., 0.], 
     [ 0., 0., 0., 0.]]) 

In [343]: size 
Out[343]: 5 
4

您可以使用hstackvstack來連接陣列:

>>> 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]])