w3resource

NumPy: Copy data from a given array to another array

NumPy: Array Object Exercise-148 with Solution

Write a NumPy program to copy data from a given array to 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 integers
x = np.array([24, 27, 30, 29, 18, 14])

# Displaying a message indicating the original array will be printed
print("Original array:")

# Printing the original array 'x'
print(x)

# Creating an empty array 'y' with the same shape and dtype as 'x'
y = np.empty_like(x)

# Copying the contents of 'x' to array 'y'
y[:] = x

# Displaying a message indicating the copied array will be printed
print("\nCopy of the said array:")

# Printing the copied array 'y'
print(y) 

Sample Output:

Original array:
[24 27 30 29 18 14]

Copy of the said array:
[24 27 30 29 18 14]

Explanation:

In the above example -

  • x = np.array([24, 27, 30, 29, 18, 14]): It creates a 1-dimensional NumPy array x with the given elements.
  • y = np.empty_like(x): It creates a new NumPy array y with the same shape as x and uninitialized elements. In this case, y is also a 1-dimensional array with a length of 6.
  • y[:] = x: It uses slice assignment to copy the elements from the array x to the array y. The colon : in y[:] represents a slice of the entire array y, so this line of code assigns all elements in x to the corresponding positions in y.

Finally print() function prints the array ‘y’.

Pictorial Presentation:

NumPy: Copy data from a given array to another array

Python-Numpy Code Editor:

Previous: Write a NumPy program to create an array that represents the rank of each item of a given array.
Next: Write a NumPy program to find elements within range from a given array of numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-148.php