NumPy: Boolean array with 1 bit entries

Learn, how to create a NumPy array of boolean values that just uses 1 bit?
By Pranit Sharma Last updated : December 22, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Overview

In programming, we sometimes use some specific values that only have two values, either True/False or 0/1. These values are known as Boolean values.

Since we need to create a numpy array with 1-bit entries, it is not appropriate to use the standard np.bool type because this type is of size 1 byte (8 bits) and it will consume 8 times the memory we require.

We can use 0 and 1 values since they fall under the binary form but again if we assign np.bool data type the size of these values will become 8 bits.

NumPy Boolean array with 1 bit entries

For this purpose, we will first create an array with 0 and 1 values and also we will assign the data type as bool but we will use numpy's packbits() and unpackbits() methods.

The packbits() packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end.

For reconstructing from packed data, use the unpackbits() method, .resize, .reshape, and .view(bool).

Let us understand with the help of an example,

Python code to create a NumPy array of boolean values that just uses 1 bit

import numpy as np

# original boolean array
arr1 = np.array(
    [
        [0, 1, 1, 0, 1],
        [0, 0, 1, 1, 1],
        [1, 1, 1, 1, 1],
    ],
    dtype=bool,
)

# Display original array
print("Original Array:\n", arr1, "\n")

# packed data
packed_data = np.packbits(arr1, axis=None)

# checking the size
print(len(arr1.tobytes()))  # 15 bytes
print(len(packed_data.tobytes()))  #  2 bytes (ceil(15/8))

# reconstructing from packed data. You need to resize and reshape
unpacked_data = (
    np.unpackbits(packed_data, count=arr1.size).reshape(arr1.shape).view(bool)
)

# and the arrays are equal
print(np.array_equal(arr1, unpacked_data))  # True

Output

Original Array:
 [[False  True  True False  True]
 [False False  True  True  True]
 [ True  True  True  True  True]] 

15
2
True

Reference: stackoverflow.com

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.