2014-03-29 14 views
25

in Matlab mache ich das:verketten leeres Array in Numpy

>> E = []; 
>> A = [1 2 3 4 5; 10 20 30 40 50]; 
>> E = [E ; A] 

E = 

    1  2  3  4  5 
    10 20 30 40 50 

Jetzt möchte ich die gleiche Sache in Numpy aber ich habe Probleme, schau mal:

>>> E = array([],dtype=int) 
>>> E 
array([], dtype=int64) 
>>> A = array([[1,2,3,4,5],[10,20,30,40,50]]) 

>>> E = vstack((E,A)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/shape_base.py", line 226, in vstack 
    return _nx.concatenate(map(atleast_2d,tup),0) 
ValueError: array dimensions must agree except for d_0 

ich eine ähnliche Situation haben wenn ich das mit:

>>> E = concatenate((E,A),axis=0) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: arrays must have same number of dimensions 

Oder:

>>> E = append([E],[A],axis=0) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/function_base.py", line 3577, in append 
    return concatenate((arr, values), axis=axis) 
ValueError: arrays must have same number of dimensions 
+0

In MATLAB-Arrays sind immer 2D oder größer. In numpy können sie 1 oder sogar 0 Dimensionen haben. – hpaulj

Antwort

34

, wenn Sie die Anzahl der Spalten vor der Hand wissen:

>>> xs = np.array([[1,2,3,4,5],[10,20,30,40,50]]) 
>>> ys = np.array([], dtype=np.int64).reshape(0,5) 
>>> ys 
array([], shape=(0, 5), dtype=int64) 
>>> np.vstack([ys, xs]) 
array([[ 1., 2., 3., 4., 5.], 
     [ 10., 20., 30., 40., 50.]]) 

wenn nicht:

>>> ys = np.array([]) 
>>> ys = np.vstack([ys, xs]) if ys.size else xs 
array([[ 1, 2, 3, 4, 5], 
     [10, 20, 30, 40, 50]]) 
-3

np.concatenate, np.hstack und np.vstack wird tun, was Sie wollen. Beachten Sie jedoch, dass NumPy-Arrays nicht zur Verwendung als dynamische Arrays geeignet sind. Verwenden Sie stattdessen Python-Listen für diesen Zweck.