Skip to main content
Practice

Data Type Conversion and Copying Arrays

Every NumPy array has a fixed data type (e.g., int, float, or bool).

You can change an array’s type using .astype().

When copying arrays, it’s crucial to understand the difference between creating a real copy and merely referencing the same data in memory.


Changing Data Type with .astype()

Convert an array from one type to another:

Changing Data Type with .astype()
arr = np.array([1.5, 2.8, 3.0])
int_arr = arr.astype(int)

print(int_arr) # [1 2 3]

This converts float values into integers.


Copying Arrays

Assigning one array to another does not create a real copy. Both variables point to the same data.

Copying Arrays
a = np.array([1, 2, 3])
b = a # Not a copy!
b[0] = 99

print(a) # [99 2 3] original was modified

Use .copy() to create a true copy:

Copying Arrays
c = a.copy()
c[0] = 0

print(a) # Still [99 2 3]

Summary

  • Use .astype() to change data types (e.g., float to int).
  • Use .copy() to create a real copy of an array.
  • Without .copy(), both variables refer to the same array in memory.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.