Numpy Arrays: Exercises


2. Modifying NumPy Arrays. In Python, you can modify a NumPy array by changing, adding, or removing items. To change an item, use indexing and assignment. To add items, you can use methods like numpy.append(). To remove items, you can use methods like numpy.delete().

For example, you can change the second item in a NumPy array like this: numbers[1] = 6.


# Import the NumPy library import numpy as np # Create a NumPy array of numbers numbers = np.array([1, 2, 3, 4, 5]) # Modify the third item in the array numbers[2] = ___ # Add a new number to the end of the array numbers = np.append(numbers, ___) # Remove the first number from the array numbers = np.delete(numbers, ___) # Print the modified array print(numbers) # Import the NumPy library import numpy as np # Create a NumPy array of numbers numbers = np.array([1, 2, 3, 4, 5]) # Modify the third item in the array numbers[2] = 7 # Add a new number to the end of the array numbers = np.append(numbers, 6) # Remove the first number from the array numbers = np.delete(numbers, 0) # Print the modified array print(numbers) test_object("numbers") success_msg("You have correctly modified the NumPy.")
To modify a NumPy array, use indexing for changes and NumPy methods for additions and removals.

Previous Exercise Next Exercise