w3resource

NumPy: Add a new row to an empty numpy array


Add Row to Empty Array

Write a NumPy program to add another row to an empty NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating an empty NumPy array with shape (0, 3) of integers
arr = np.empty((0, 3), int)

# Printing a message indicating an empty array will be displayed
print("Empty array:")

# Displaying the empty array
print(arr)

# Appending two new arrays to the 'arr' array vertically along axis 0
arr = np.append(arr, np.array([[10, 20, 30]]), axis=0)
arr = np.append(arr, np.array([[40, 50, 60]]), axis=0)

# Printing a message indicating that two new arrays are added to the original array
print("After adding two new arrays:")

# Displaying the updated 'arr' array after adding two new arrays
print(arr) 

Sample Output:

Empty array:
[]
After adding two new arrays:
[[10 20 30]
 [40 50 60]]

Explanation:

In the above exercise -

  • arr = np.empty((0,3), int): This line creates an empty NumPy array named ‘arr’ with shape (0, 3) and integer data type. The array has no rows and 3 columns.
  • arr = np.append(arr, np.array([[10,20,30]]), axis=0): Append a new row [10, 20, 30] to the ‘arr’ array along axis 0 (row-wise). After this operation, the shape of ‘arr’ becomes (1, 3).
  • arr = np.append(arr, np.array([[40,50,60]]), axis=0): Append another row [40, 50, 60] to the ‘arr’ array along axis 0 (row-wise). After this operation, the shape of ‘arr ‘ becomes (2, 3).
  • Finally print(arr) function prints the array.

Pictorial Presentation:

Python NumPy: Find the position of the index of a specified value greater than existing value in numpy array

For more Practice: Solve these Related Problems:

  • Write a NumPy program to initialize an empty array and then append a new row using np.vstack.
  • Create a function that checks if an array is empty and adds a row only if it meets certain conditions.
  • Test the row addition on an empty array and verify that the shape is updated correctly.
  • Implement a solution that dynamically adds multiple rows to an empty array and prints the result.

Go to:


PREV : Find Index of Higher Ranked Value in Array
NEXT : Get Index of Max Element Along Axis


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.