Lecture

Data Type Conversion and Copying Arrays

NumPy arrays have a fixed data type, like int, float, or bool.
You can change the type using .astype().

Also, when copying arrays, it’s important to know the difference between a real copy and just a reference.


Changing Data Type with .astype()

You can convert an array from one type to another:

arr = np.array([1.5, 2.8, 3.0]) int_arr = arr.astype(int) print(int_arr) # [1 2 3]

This turns float values into integers.


Copying Arrays

By default, assigning one array to another does not create a real copy — they both point to the same data.

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 make a true copy:

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

What’s Next

You’ll now practice converting types and copying arrays safely in Jupyter.

Quiz
0 / 1

What is the correct method to create a true copy of a NumPy array?

Assign the array to a new variable.

Use the .astype() method.

Use the .copy() method.

Use the .clone() method.

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help