Geek Slack

Learn Numerical Python
About Lesson


NumPy Data Types


NumPy Data Types

NumPy supports a wide variety of data types that you can use to define the elements of your arrays. These data types include integers, floats, complex numbers, booleans, and more.

Checking the Data Type of an Array

You can check the data type of a NumPy array using the dtype attribute.

Example: Checking Data Type

import numpy as np

# Creating an array
arr = np.array([1, 2, 3, 4, 5])

# Checking the data type
print(arr.dtype)  # Output: int64 (or int32 depending on the system)

Specifying Data Types

When creating a NumPy array, you can specify the data type using the dtype parameter.

Example: Specifying Data Type

import numpy as np

# Creating an array with float data type
arr = np.array([1, 2, 3, 4, 5], dtype='float32')

print(arr)
print(arr.dtype)  # Output: float32

Common NumPy Data Types

NumPy provides many data types, including:

  • int8, int16, int32, int64: Signed integers
  • uint8, uint16, uint32, uint64: Unsigned integers
  • float16, float32, float64: Floating-point numbers
  • complex64, complex128: Complex numbers
  • bool: Boolean
  • str: String

Example: Using Different Data Types

import numpy as np

# Integer array
arr_int = np.array([1, 2, 3], dtype='int16')
print(arr_int)
print(arr_int.dtype)  # Output: int16

# Unsigned integer array
arr_uint = np.array([1, 2, 3], dtype='uint16')
print(arr_uint)
print(arr_uint.dtype)  # Output: uint16

# Float array
arr_float = np.array([1.1, 2.2, 3.3], dtype='float32')
print(arr_float)
print(arr_float.dtype)  # Output: float32

# Complex array
arr_complex = np.array([1+2j, 3+4j], dtype='complex64')
print(arr_complex)
print(arr_complex.dtype)  # Output: complex64

Type Conversion

You can convert the data type of an existing array using the astype method.

Example: Type Conversion

import numpy as np

# Creating an integer array
arr = np.array([1, 2, 3, 4])

# Converting to float
arr_float = arr.astype('float32')
print(arr_float)
print(arr_float.dtype)  # Output: float32

# Converting to boolean
arr_bool = arr.astype('bool')
print(arr_bool)
print(arr_bool.dtype)  # Output: bool

Handling Strings

NumPy arrays can also handle string data types, but they are not as efficient as numeric data types.

Example: String Data Type

import numpy as np

# Creating a string array
arr = np.array(['apple', 'banana', 'cherry'], dtype='str')
print(arr)
print(arr.dtype)  # Output: 

Conclusion

Understanding and using the correct data types in NumPy arrays is crucial for optimizing performance and ensuring correct data manipulation. By specifying and converting data types, you can handle a variety of numerical and non-numerical data efficiently.

Join the conversation