NumPy: Take values from a source array and put them at specified indices of another array
Use put to Place Values in Array
Write a NumPy program to take values from a source array and put them at specified indices of another array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a NumPy array 'x' containing floating-point values
x = np.array([10, 10, 20, 30, 30], float)
# Printing the original array 'x'
print(x)
# Printing a message indicating the modification of the array
print("Put 0 and 40 in first and fifth position of the above array")
# Creating a NumPy array 'y' containing floating-point values [0, 40, 60]
y = np.array([0, 40, 60], float)
# Using the 'put()' method to replace values in 'x' at positions 0 and 4 with values from array 'y'
x.put([0, 4], y)
# Printing a message indicating the display of the modified array 'x' after putting two values at specific positions
print("Array x, after putting two values:")
print(x)
Sample Output:
[ 10. 10. 20. 30. 30.] Put 0 and 40 in first and fifth position of the above array Array x after put two values: [ 0. 10. 20. 30. 40.]
Explanation:
In the above example –
‘x = np.array([10, 10, 20, 30, 30], float)’ creates a NumPy array 'x' with the elements 10, 10, 20, 30, and 30 of float data type.
‘y = np.array([0, 40, 60], float)’ creates a new NumPy array 'y' with the elements 0, 40, and 60 of float data type. Note that the 60 is not used in this example.
x.put([0, 4], y): Use the put function to replace the values at indices 0 and 4 in the 'x' array with the values from the 'y' array. The first and second values from 'y' (0 and 40) are used to replace the values at indices 0 and 4 in 'x', respectively.
Finally print() function prints the modified 'x' array. The output will be [0, 10, 20, 30, 40].
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