Python for Data Science: Chapter 5: NumPy and Pandas Libraries

NumPy: Copying Arrays

Python library

An array copy in NumPy means creating a new array that has the same data as the original array, but is stored separately in memory.

Copying Arrays

• An array copy in NumPy means creating a new array that has the same data as the original array, but is stored separately in memory.

To create a copy, we use the function

new_array = old_array.copy()

This creates another array having same data values but they are stored in different memory locations.

 

Python program

import numpy as np

arr1 = np.array([100,200,300])

arr2 = arr1.copy()

print("After copy operation...")

print("arr1: ",arr1)

print("arr2: ",arr2)

arr2[0]=500

print("After modification...")

print("arr1: ",arr1)

print("arr2: ",arr2)

Output

After copy operation...

arr1: [100 200 300]

arr2: [100 200 300]

After modification...

arr1: [100 200 300]

arr2: [500 200 300]

Note that in above code, arr1 and arr2 now exist independently. Changing arr2 does not change arr1.

 

Review Question

1. What happens if you modify an array created using .copy () ?

 

Python for Data Science: Chapter 5: NumPy and Pandas Libraries : Tag: Computer Programming, Python, Data Science : Python library - NumPy: Copying Arrays


Python for Data Science: Chapter 5: NumPy and Pandas Libraries



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation