In this article, we will cover how to append a NumPy array to an empty array in Python. Here, we will discuss 2 different methods to append into an empty NumPy array. Both of these methods differ slightly, as shown below:
Append a NumPy array to an empty array using the append
Example 1
Here we are creating an empty array and then appending it to the array.
Python3
import numpy as np l = np.array([]) l = np.append(l, np.array([ 'G' , 'F' , 'G' ])) l = np.append(l, np.array([ 'G' , 'F' , 'G' ])) print (l) |
Output:
['G' 'F' 'G' 'G' 'F' 'G']
Example 2
Here we are creating an empty array and then appending an empty row in it to see if there is any difference.
Python3
import numpy as np l = np.array([]) l = np.append(l, np.array([])) l = np.append(l, np.array([ 'G' , 'F' , 'G' ])) l = np.append(l, np.array([ 'G' , 'F' , 'G' ])) print (l) |
Output:
We can see that there is no difference in output.
['G' 'F' 'G' 'G' 'F' 'G']
Append a NumPy array to an empty array using hstack and vstack
Here we are using the built-in functions of the NumPy library np.hstack and np.vstack. Both are very much similar to each other as they combine NumPy arrays together. The major difference is that np.hstack combines NumPy arrays horizontally and np. vstack combines arrays vertically.
Python3
import numpy as np arr = np.array([]) arr = np.hstack((arr, np.array([ 'G' , 'F' , 'G' ]))) print (arr) arr = np.vstack((arr, np.array([ 'G' , 'F' , 'G' ]))) print (arr) |
Output:
['G' 'F' 'G'] [['G' 'F' 'G'] ['G' 'F' 'G']]