[go: up one dir, main page]

0% found this document useful (0 votes)
4 views2 pages

Numpy Datatype

The document explains how to identify and change the data type of a NumPy array using the dtype attribute and the astype() method. It also demonstrates how to convert a numeric array into a categorical array by mapping numeric values to categories. Key points include the use of dtype for checking data types and efficient mapping of numeric arrays using dictionary mapping.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Numpy Datatype

The document explains how to identify and change the data type of a NumPy array using the dtype attribute and the astype() method. It also demonstrates how to convert a numeric array into a categorical array by mapping numeric values to categories. Key points include the use of dtype for checking data types and efficient mapping of numeric arrays using dictionary mapping.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like