NumPy: Boolean array with 1 bit entries

Learn, how to create a NumPy array of boolean values that just uses 1 bit?
Submitted by Pranit Sharma, on February 19, 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.

Boolean array with 1 bit entries

We know that numpy.linspace() is used to create an array using start, stop, and num whereas numpy.arange() is used to create an array using start, stop and step.

We need to find a way so we can blend the functionalities of linspace and arange so that we can create an array using start, step, and num.

For this purpose, we will define the start, step, and num before creating the array and then numpy.arange() will help us.

We will create a numpy array using numpy.arange() where will pass the num value and multiply the result with the sum of the start and step.

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
import numpy as np

# Creating a numpy array
arr = np.array([[[1,0,1],[0,1,0]],
                [[1,1,0],[0,0,1]]])

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

# packing bits
res = np.packbits(arr,axis=1)

# Display result
print("Result:\n",res,"\n")

# Display size of array
print("Total bits in array:\n",res.size)

Output:

Example: NumPy: Boolean array with 1 bit entries

Python NumPy Programs »





Comments and Discussions!










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