w3resource

NumPy: Copy data from a given array to another array


Copy Data to Another Array

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to create an exact copy of a given array using the copy() method and verify independence.
  • Create a function that duplicates an array and then modifies the original to ensure the copy remains unchanged.
  • Test copying on multi-dimensional arrays and compare the memory addresses of the original and copied arrays.
  • Implement a solution that uses both shallow and deep copy techniques and explains the differences through testing.

Go to:


PREV : Rank Items in Array
NEXT : Find Elements in a Specified Range


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.