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 Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics