Identifying and Changing Data Type in NumPy
How to Identify the Data Type of a NumPy Array?
In NumPy, you can identify the data type of a given array using the dtype attribute.
Example:
import numpy as np
# Creating an array
arr = np.array([1, 2, 3, 4, 5])
# Identifying the data type
print(arr.dtype)
Output:
int64 (or int32 depending on system)
How to Change the Data Type of a NumPy Array?
You can change the data type of an array using the astype() method.
Example:
# Converting integer array to float
double_arr = arr.astype(float)
print(double_arr)
print(double_arr.dtype)
Output:
[1. 2. 3. 4. 5.]
float64
Convert a Numeric Array to a Categorical (Text) Array
We can map numeric values to categories using NumPy functions.
Example:
# Creating a numeric array
num_array = np.array([1, 2, 1, 3, 2, 3])
# Mapping numbers to categories
category_map = {1: 'Low', 2: 'Medium', 3: 'High'}
categorical_array = np.vectorize(category_map.get)(num_array)
print(categorical_array)
Output:
['Low' 'Medium' 'Low' 'High' 'Medium' 'High']
Conclusion
- The dtype attribute helps to check the data type of an array.
- The astype() method allows conversion of data types.
- NumPy provides efficient ways to map numeric arrays into categorical arrays using dictionary
mapping.
End of Answer