Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

How might I make an empty array which I can then hstack with the another array to load up with values? 

For instance in Matlab, I can do the accompanying: 

a = [];

b = [10 20];

a = [a b];

and I get

a = 

      10    20

Now, I'm looking for something which is similar in numpy. 

I tried

a = np.array([]);

b = np.array([10, 20]);

a = np.hstack((a, b)); # should be equal to `b`

Which gives

ValueError: all the input array dimensions except for the concatenation axis must match exactly

1 Answer

0 votes
by (26.4k points)

With the help of np.array([]) with hstack, This 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 state of the underlying a requirements some tweaking to cause it to 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 utilized dtype=int while making the underlying value of a. Without this, it utilizes the default dtype of float, and afterward when an is hstacked or vstacked with b, the outcome is upcast to float.

Wanna become a Python expert? Come and join the python certification course and get certified.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...