NUMPY Tutorial



NumPy ASTYPE()


πŸ” NumPy astype() – Convert Array Data Type

NumPy’s astype() method is used to convert the data type of an existing array to another type. This is useful when you want to reduce memory usage or ensure consistency in calculations.

βœ… Syntax

new_array = original_array.astype(new_dtype)

Note: astype() always returns a new array β€” it doesn’t change the original array.

πŸ“˜ Example 1: Float to Integer

import numpy as np

arr = np.array([1.5, 2.3, 3.9])
new_arr = arr.astype(int)
print(new_arr)

Output:

[1 2 3]

πŸ“˜ Example 2: Integer to String

arr = np.array([10, 20, 30])
new_arr = arr.astype(str)
print(new_arr)

Output:

['10' '20' '30']

⚠️ Example 3: Incompatible Conversion

If you try to convert a string to an integer and it contains non-numeric characters, you'll get an error:

arr = np.array(['a', 'b', 'c'])
new_arr = arr.astype(int)  # ❌ This will raise an error
🚫 ValueError: invalid literal for int() with base 10: 'a'

🧠 Why Use astype()?

  • To optimize memory by converting to smaller data types (e.g., float64 β†’ float32)
  • To ensure consistent types for mathematical operations
  • To prepare data for machine learning or visualization tools

πŸ“‹ Supported Type Strings

You can pass data types as Python types (int, float) or NumPy type strings:

  • 'int32', 'int64'
  • 'float32', 'float64'
  • 'bool', 'str', 'complex'
βœ… Next Up: Learn about NumPy Indexing and Slicing ➑️

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review