Reputation: 36765
How can I create an empty array wich I can then hstack
with another array to fill with values?
For example in Matlab, I can do the following:
a = [];
b = [10 20];
a = [a b];
and would get
a =
10 20
I am looking for something similar in numpy. I tried
a = np.array([]);
b = np.array([10, 20]);
a = np.hstack((a, b)); # should be equal to `b`
But that gives
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Upvotes: 0
Views: 5896
Reputation: 114841
Using np.array([])
with hstack
works for me.
In [11]: a = array([], dtype=int)
In [12]: b = array([10, 20])
In [13]: c = array([30, 40])
In [14]: a = hstack((a,b))
In [15]: a
Out[15]: array([10, 20])
In [16]: a = hstack((a,c))
In [17]: a
Out[17]: array([10, 20, 30, 40])
For vstack
, the shape of the initial a
needs some tweaking to make it have shape (0,2):
In [22]: a = array([], dtype=int).reshape(-1,2)
In [23]: a
Out[23]: array([], shape=(0, 2), dtype=int64)
In [24]: b
Out[24]: array([10, 20])
In [25]: c
Out[25]: array([30, 40])
In [26]: a = vstack((a,b))
In [27]: a
Out[27]: array([[10, 20]])
In [28]: a = vstack((a,c))
In [29]: a
Out[29]:
array([[10, 20],
[30, 40]])
Note that I've used dtype=int
when creating the initial value of a
. Without this, it uses the default dtype of float
, and then when a
is hstack
ed or vstack
ed with b
, the result is upcast to float.
Upvotes: 2