NumPy Data Types

M.Ramya

 Built-in Data Types in Python

Python provides several built-in data types by default to handle different kinds of data. Here are some of the most commonly used ones:

String (str): Used to represent text. Strings are enclosed in quotation marks.

Example: "Hello, World!", 'Python'

Integer (int): Represents whole numbers, both positive and negative.

Example: -3, 0, 42

Float (float): Used for representing real (decimal) numbers.

Example: 3.14, 0.99, -100.5Boolean (bool): Represents one of two values — True or False.

Example: True, False

Complex (complex): Used to represent complex numbers, which include a real and an imaginary part.

Example: 1 + 2j, 3.5 + 4.5j

Data Types in NumPy

NumPy extends Python’s built-in data types with additional types specifically designed for numerical computing. These data types are often represented by single-character codes for efficiency.

Below is a list of commonly used NumPy data types along with their character codes:

i – Integer

Used for signed integer numbers.

Example: int8, int16, int32, int64

u – Unsigned Integer

Represents non-negative integers.

Example: uint8, uint16

f – Float

Used for floating-point (decimal) numbers.

Example: float16, float32, float64

c – Complex Float

Represents complex numbers with float components.

Example: complex64, complex128

b – Boolean

Used to represent True or False.

m – Timedelta

Represents differences in time (durations).

M – Datetime

Used for date and time representation.

O – Object

Generic Python objects (useful for mixed types).

S – String

Represents byte strings (ASCII-encoded).

U – Unicode String

Used for Unicode text data.

V – Void

A fixed-size raw chunk of memory, often used for custom or structured data.

Checking the Data Type of a NumPy Array

In NumPy, every array has a special property called dtype that reveals the data type of its elements.

Program:

Get the data type of an array:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr.dtype)

This will display the data type of the array arr.a

Output :

int64

Program:

import numpy as np

arr = np.array(['apple', 'banana', 'cherry'])

print(arr.dtype)

Output:

<U6

Creating Arrays with a Specific Data Type

In NumPy, we can create arrays using the array() function. This function includes an optional parameter called dtype that allows us to specify the desired data type for the array elements.

Program:

Create an array with elements of string data type:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='S')

print(arr)

print(arr.dtype)

Output:

[b'1' b'2' b'3' b'4'] 

|S1

Program:

Create an array with elements of 4-byte integer data type:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='i4')

print(arr)

print(arr.dtype)

Output:

[1234]

int34

What Happens if a Value Cannot Be Converted?

If you specify a data type (dtype) that cannot accommodate certain elements in the array, NumPy will raise a ValueError.

What is a ValueError?

In Python, a ValueError occurs when a function receives an argument of the correct type, but with an inappropriate or invalid value.

Example:

Trying to convert a non-numeric string, such as 'a', to an integer will result in a ValueError:

import numpy as np

arr = np.array(['a', '2', '3'], dtype='i') 

 # This will raise a ValueError

You can specify the desired data type either as:

A string, such as 'i' for integer or 'f' for float.

A Python data type, like int or float.

Converting Data Type of Existing Arrays

The recommended way to change the data type of an existing NumPy array is by using the astype() method.

The astype() method returns a copy of the array with the specified data type.

Program:

Float to integer by using 'i' as parameter value:

import numpy as np
# Create an array with float values
arr = np.array([1.1, 2.1, 3.1])
# Convert the array to integers using 'i' as the parameter value
newarr = arr.astype('i')
# Print the new array and its data type
print(newarr)
print(newarr.dtype)

Output:

[1 2 3]
int32

Program:

Convert Data Type from Float to Integer

import numpy as np
arr = np.array([1.1, 2.1, 3.1])
# Convert float to integer
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)

Output:

[1 2 3]
int64

Program;

Convert Data Type from Integer to Boolean

import numpy as np
arr = np.array([1, 0, 3])
# Convert integer to boolean
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

Output:

[True False True]
bool
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send