Skip to main content

Python – Boolean Array in NumPy

In this article, I’ll be explaining how to generate boolean arrays in NumPy and utilize them in your code.

In NumPy, boolean arrays are straightforward NumPy arrays with array components that are either “True” or “False.”

Note: 0 and None are considered False and everything else is considered True.

Examples:

Input: arr = [1, 0, 1, 0, 0, 1, 0]
Output: [True, False, True, False, False, True, False]
Explanation: 1 is considered as True and 0 is considered as False.

Input: arr = [5, None, 1, 25, -10, 0, ‘A’]
Output: [ True False  True  True  True False  True]

Method 1: Using dtype

Every ndarray has an associated data type (dtype) object. This data type object informs us about the layout of the array. This means it gives us information about:

  • Type of the data (integer, float, Python object, etc.)
  • Size of the data (number of bytes)
  • The byte order of the data (little-endian or big-endian)
  • If the data type is a sub-array, what is its shape and data type?

The values of a ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes. So how these bytes will be interpreted is given by the dtype object.

Python3




import numpy as np
  
arr = np.array([1, 0, 1, 0, 0, 1, 0])
  
print(f'Original Array: arr')
  
bool_arr = np.array(arr, dtype='bool')
  
print(f'Boolean Array: bool_arr')

Output:

Original Array: [1 0 1 0 0 1 0]
Boolean Array: [ True False  True False False  True False]

When the elements are not 0 and 1:

Python3




import numpy as np
  
arr = np.array([5, None, 1, 25, -10, 0, 'A'])
  
print(f'Original Array: arr')
  
bool_arr = np.array(arr, dtype='bool')
  
print(f'Boolean Array: bool_arr')

Output:

Original Array: [5 None 1 25 -10 0 'A']
Boolean Array: [ True False  True  True  True False  True]

Method 2: Using astype

It is a method used to cast a pandas object to a specified dtype. The astype() function also provides the capability to convert any suitable existing column to a categorical type.

Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)

Parameters:
dtype : Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use col: dtype, …, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.
copy : Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).

errors : Control raising of exceptions on invalid data for provided dtype.
raise : allow exceptions to be raised
ignore : suppress exceptions. On error return original object

kwargs :keyword arguments to pass on to the constructor

Returns: casted : type of caller

Python3




import numpy as np
  
arr = np.array([1, 0, 1, 0, 0, 1, 0])
  
print(f'Original Array: arr')
  
bool_arr = np.array(arr).astype(bool)
  
print(f'Boolean Array: bool_arr')

Output:

Original Array: [1 0 1 0 0 1 0]
Boolean Array: [ True False  True False False  True False]

When the elements are not 0 and 1:

Python3




import numpy as np
  
arr = np.array([5, None, 1, 25, -10, 0, 'A'])
  
print(f'Original Array: arr')
  
bool_arr = np.array(arr).astype(bool)
  
print(f'Boolean Array: bool_arr')

Output:

Original Array: [5 None 1 25 -10 0 'A']
Boolean Array: [ True False  True  True  True False  True]

https://neveropen.tech/python-boolean-array-in-numpy/?feed_id=37&_unique_id=683cc0e71bc36

Comments

Popular posts from this blog

Bare Metal Billing Client Portal Guide

Contents Order a Bare Metal Server My Custom / Contract Pricing View Contract Details Location Management Order History & Status View Order Details Introduction The phoenixNAP Client Portal allows you to purchase bare metal servers and other phoenixNAP products and services. Using the intuitive interface and its essential tools, you can also easily manage your infrastructure. This quick guide will show you how to use the new form to order a bare metal server and how to navigate through new bare metal features within the phoenixNAP Client Portal. Order a Bare Metal Server An order form is an accordion-based process for purchasing phoenixNAP products. Our order form allows you to view the pricing and order multiple products from the same category at the same time. Note: The prices on the form are per month . A contract is not required. However, if you want a contracted price, you may be eligible for a discount depending on the quantity and ...

Add an element in Array to make the bitwise XOR as K

Given an array arr[] containing N positive integers, the task is to add an integer such that the bitwise Xor of the new array becomes K. Examples: Input: arr[] = 1, 4, 5, 6, K = 4 Output: 2 Explanation: Bit-wise XOR of the array is 6.  And bit-wise XOR of 6 and 2 is 4. Input: arr[] = 2, 7, 9, 1, K = 5 Output: 8   Approach: The solution to the problem is based on the following idea of bitwise Xor: If for two numbers X and Y , the bitwise Xor of X and Y is Z then the bitwise Xor of X and Z is Y. Follow the steps to solve the problem: Let the bitwise XOR of the array elements be X .  Say the required value to be added is Y such that X Xor Y = K . From the above observation, it is clear that the value to be added (Y) is the same as X Xor K . Below is the implementation of the above approach: C++ // C++ code to implement the above approach   #include using namespace std;   // Function to find the required value int find_...

Mahotas – Template Matching

In this article we will see how we can do template matching in mahotas. Template is basically a part or structure of image. In this tutorial we will use “lena” image, below is the command to load it.   mahotas.demos.load('lena') Below is the lena image      In order to do this we will use mahotas.template_match method Syntax : mahotas.template_match(img, template) Argument : It takes image object and template as argument Return : It returns image object    Note : Input image should be filtered or should be loaded as grey In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this   image = image[:, :, 0] Below is the implementation    Python3 # importing required libraries import mahotas import mahotas.demos from pylab import gray, imshow, show import numpy as np import matplotlib.pyplot as plt      # loading image ...