NumPy: Add a new row to an empty numpy array
NumPy: Array Object Exercise-119 with Solution
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:
Previous: Write a NumPy program to find the position of the index of a specified value greater than existing value in numpy array.
Next: Write a NumPy program to get the index of a maximum element in a numpy array along one axis.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-119.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics