Add a new row to an empty numpy array in Python
This tutorial will cover how we can generate an empty NumPy array, and various methods to add specific rows to this empty array in Python.
Create an empty Numpy Array and append rows in Python
We will do this using three different methods. Let’s see them one by one.
Method 1: Using numpy.append()
There are occasions when we need to append rows to an empty array. By utilizing the numpy.append()
function, Numpy gives the ability to append a row to an empty Numpy array.
Example: Adding new rows to an empty 2-D array
import numpy as np #creating a 2D empty array empty= np.empty((0,2), int) # printing empty array print("The array : ", str(empty)) # Using append() method to add new array to the rows of our empty array empty = np.append(empty, np.array([[14,40]]), axis=0) empty = np.append(empty, np.array([[34,53]]), axis=0) print("\narray is:") print(empty)
numpy.empty()
numpy.empty(shape, dtype=float, order='C')
Shape and data type are accepted as arguments. Then, without initializing entries, it returns a new array with the specified shape and data type.
numpy.append()
numpy.append(arr, values, axis=None)
It accepts the parameters listed below,
arr
: A copy of the array to which a value must be added.
Array values must be attached to any axis, The shape must match the arr.
axis
: value-appending axis along which values must be added. Appending as a row is equal to 0 while appending as a column is equal to 1.
The output will be:
The array : [] array is: [[14 40] [34 53]]
Similarly, you can create an empty 3D array and append row-wise values in that array.
Method 2: Using np.vstack()
The series of input arrays are stacked vertically using the numpy.vstack()
method to create a single array.
Syntax : numpy.vstack(tup)
The Python Code will be:
import numpy as np #creating a 2D empty array empty= np.empty((0,3), int) # printing empty array print("The array : ", str(empty)) row = np.array([1, 2, 3]) result = np.vstack ((empty, row) ) # printing result print ("resultant array", str(result))
The output will be:
The array : [] resultant array [[1 2 3]]
Method 3: Using np.r_ method
Python Code:
import numpy as np #creating a 2D empty array empty= np.empty((0,3), int) # printing empty array print("The array : ", str(empty)) row = np.array([1, 2, 3]) result = np.r_[empty,[row]] # printing result print ("resultant array", str(result))
The output will be:
The array : [] resultant array [[1 2 3]]
So these are some methods through which we can add a new row to an empty NumPy array in Python.
Leave a Reply