Append to Empty Array in Numpy

Append to Numpy Empty Array With the
numpy.append()
Function  Append to Numpy Empty Array With the List Method in Python
This tutorial will introduce the methods to append new rows to an empty NumPy array in Python.
Append to Numpy Empty Array With the numpy.append()
Function
If we have an empty array and want to append new rows to it inside a loop, we can use the numpy.empty()
function. Since no data type is assigned to a variable before initialization in Python, we have to specify the data type and structure of the array elements while creating the empty array. This can be done inside the numpy.empty()
function. We can then append new rows to the empty array with the numpy.append()
function. See the following code example.
import numpy as np
array = np.empty((0,3), int)
array = np.append(array, np.array([[1,3,5]]), axis=0)
array = np.append(array, np.array([[2,4,6]]), axis=0)
print(array)
Output:
[[1 3 5]
[2 4 6]]
We first created an empty array and defined its structure and data type with the np.empty()
function. We then appended two rows along the 0
axis of the array
with the np.append()
function.
Append to Numpy Empty Array With the List Method in Python
We can also achieve the same goal by using the list data structure in Python. We can create empty lists and append rows to them in Python. The list.append()
function appends new elements to a list in Python. We can then convert this list to a NumPy array with the numpy.array()
function. See the following code example.
import numpy as np
list = []
list.append([1,3,5])
list.append([2,4,6])
array2 = np.array(list)
print(array2)
Output:
[[1 3 5]
[2 4 6]]
We first created an empty list list
and appended new rows to the list
with the list.append()
function. In the end, we converted the list
to the NumPy array array2
with the np.array(list)
function in Python.