Lecture

Data Type Conversion and Copying Arrays

NumPy arrays have a fixed data type, such as int, float, or bool.

You can change the type with .astype().

When copying arrays, it's also important to know the difference between creating a true copy and just referencing the same data.


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.
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