How to add a new row to an empty NumPy array?

In this tutorial, we will learn how to add a new row to an empty NumPy array? By Pranit Sharma Last updated : May 26, 2023

Problem Statement

Given an empty NumPy array, we have to add a new row in it i.e., write a Python program to add a new row to an empty NumPy array.

Adding a new row to an empty NumPy array

There are three common and efficient approaches for adding a new row to an empty NumPy array, using numpy.append(), numpy.hstack(), or numpy.r_. Let's discuss these approaches in detail.

1) Using numpy.append() Method

The numpy.append() appends values to the end of an array and it can also be used to add a new row in an empty NumPy array. You have to pass an empty array and an array with row values in it.

Syntax

arr = np.append(arr, np.array([90, 80, 70]))

Example 1

# Import numpy
import numpy as np

# Creating an empty numpy array
arr = np.array([])

# Display original array
print("Original array:\n", arr, "\n")

# Appending a new row to NumPy array
# using numpy.append() method
arr = np.append(arr, np.array([90, 80, 70]))

# Printing the updated array
print("Updated array:\n", arr)

Output

Original array:
 [] 

Updated array:
 [90. 80. 70.]

2) Using numpy.hstack() Method

The numpy.hstack() stack arrays in sequence horizontally and it can also be used to add a new row in an empty NumPy array.

Syntax

arr = np.hstack((arr, np.array([90, 80, 70])))

Example 2

# Import numpy
import numpy as np

# Creating an empty numpy array
arr = np.array([])

# Display original array
print("Original array:\n", arr, "\n")

# Appending a new row to NumPy array
# using numpy.hstack() method
arr = np.hstack((arr, np.array([90, 80, 70])))

# Printing the updated array
print("Updated array:\n", arr)

Output

Original array:
 [] 

Updated array:
 [90. 80. 70.]

3) Using numpy.r_

The numpy.r_ translates slice objects to concatenation along the first axis and it can also be used to add a new row in an empty NumPy array. You need to pass the empty array object and a new array with row values.

Syntax

arr = np.r_[arr, np.array([90, 80, 70])]

Example 3

# Import numpy
import numpy as np

# Creating an empty numpy array
arr = np.array([])

# Display original array
print("Original array:\n", arr, "\n")

# Appending a new row to NumPy array
# using numpy.r_
arr = np.r_[arr, np.array([90, 80, 70])]

# Printing the updated array
print("Updated array:\n", arr)

Output

Original array:
 [] 

Updated array:
 [90. 80. 70.]

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.