- Python Boolean array in NumPy
- Boolean Array using dtype=’bool’ in NumPy – Python
- Boolean Array using comparison in NumPy
- Converting to numpy boolean array using .astype(bool)
- Библиотека Numpy. Использование boolean массива для доступа к ndarray
- Создание boolean массивов
- Использование boolean массивов для получения выборок
- Индексация с использованием boolean выражения
- Модификация элементов ndarray с использованием boolean массивов
- P.S.
- Numpy Boolean Array – Easy Guide for Beginners
- Declaring a Numpy Boolean Array
- Numpy Boolean Array – Relational Operations
- Numpy Boolean Array – Logical Operations
- Numpy Boolean Array Index
- Conclusion
Python Boolean array in NumPy
In this post, I will be writing about how you can create boolean arrays in NumPy and use them in your code.
Boolean arrays in NumPy are simple NumPy arrays with array elements as either ‘True’ or ‘False’. Other than creating Boolean arrays by writing the elements one by one and converting them into a NumPy array, we can also convert an array into a ‘Boolean’ array in some easy ways, that we will look at here in this post.
In this process, all elements other than 0, None and False all are considered as True.
Boolean Array using dtype=’bool’ in NumPy – Python
import numpy as np import random array = [] for _ in range(10): num = random.randint(0,1) array.append(num) print(f'Original Array=') # prints the original array with 0's and 1's nump_array = np.array(array,dtype='bool') print(f'numpy boolean array:') # prints the converted boolean array
Here the output will look somewhat like this:
output:
Boolean Array using comparison in NumPy
import numpy as np import random array = np.arange(10,30) print('1st array=',array,'\n') array_bool = array > 15 print(f'First boolean array by comparing with an element:\n\n\n') array_2 = [random.randint(10,30) for i in range(20)] # second array using list comprehension print(f'Second array:\n') array2_bool = array_2 > array print(f'second boolean array by comparing second array with 1st array:\n')
In the above piece of code, I have formed the ‘array’ is created using numpy.arrange() function. And the elements are from 10 to 30 (20 elements).
Now form the boolean array (array_bool) by comparing it with 15 if the elements are greater than 15 they are noted as True else False.
The second array is created using simple, ‘List comprehension’ technique. And of the same length as the ‘array’ and elements are random in the range 10 to 30(inclusive). Now the second boolean array is created using comparison between the elements of the first array with the second array at the same index.
Output:
**Note: This is known as ‘Boolean Indexing’ and can be used in many ways, one of them is used in feature extraction in machine learning. Or simply, one can think of extracting an array of odd/even numbers from an array of 100 numbers.
Converting to numpy boolean array using .astype(bool)
For example, there is a feature array of some images, and you want to just store the bright pixels and eliminate the dark pixels(black=0). You can do this by converting the pixels array to boolean and use the Boolean array indexing to eliminate the black pixels!
Example:
import numpy import random random.seed(0) arr_1 = [random.randint(0,1) for _ in range(20)] print(f'Original Binary array:\n\n') arr_bool = numpy.array(arr_1).astype(bool) print(f'Boolean Array:\n')
Output:
Библиотека Numpy. Использование boolean массива для доступа к ndarray
Рассмотрим мощный инструмент для доступа к данным ndarray в библиотеке Numpy – boolean массивы. С их помощью можно получать подвыборки и модифицировать данные в исходном массиве.
Создание boolean массивов
В одном из предыдущих уроков (Библиотека Numpy . Работа с массивами. Слайсы ) мы рассматривали различные способы получения элементов из ndarray . Но на этом варианты не заканчиваются. Использование boolean массивов для доступа к данным порой является более лучшим вариантом, чем использование численных индексов.
Для начала создадим несколько массивов, с которыми мы будем работать.
>>> nums = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >>> letters = np.array(['a', 'b', 'c', 'd', 'a', 'e', 'b'])
Как вы знаете, в Python есть такой тип данных – boolean . Переменные этого типа принимают одно из двух значений: True или False . Такие переменные можно создать самостоятельно:
либо они могут являться результатом какого-то выражения:
Используя второй подход, можно построить на базе созданных нами в самом начале ndarray массивов массивы с элементами типа boolean .
>>> less_then_5 = nums < 5 >>> less_then_5 array([ True, True, True, True, False, False, False, False, False, False])
В этом примере мы создали boolean массив, в котором на месте элементов из nums , которые меньше пяти стоит True , в остальных случаях – False . Построим массив, в котором значение True будут иметь элементы, чей индекс совпадает с индексами, на которых стоит символ ‘a’ в массиве letters .
>>> pos_a = letters == 'a' >>> pos_a array([ True, False, False, False, True, False, False])
Далее мы изучим, каким образом можно использовать такого типа массивы на практике.
Использование boolean массивов для получения выборок
Самым замечательным в использовании boolean массивов при работе с ndarray является то, что их можно применять для построения выборок. Вернемся к рассмотренным выше примерам.
>>> less_then_5 = nums < 5 >>> less_then_5 array([ True, True, True, True, False, False, False, False, False, False])
Если мы переменную less_then_5 передадим в качестве списка индексов для nums , то получим массив, в котором будут содержаться элементы из nums с индексами равными индексам True позиций массива less_then_5 , графически это будет выглядеть так.
>>> nums[less_then_5] array([1, 2, 3, 4])
Данный подход будет работать с массивами большей размерности. Возьмем уже знакомую нам по предыдущим урокам матрицу.
>>> m = np.matrix('1 2 3 4; 5 6 7 8; 9 1 5 7') >>> print(m) [[1 2 3 4] [5 6 7 8] [9 1 5 7]]
>>> mod_m = np.logical_and(m>=3, m<=7) >>> mod_m matrix([[False, False, True, True], [ True, True, True, False], [False, False, True, True]]) >>> m[mod_m] matrix([[3, 4, 5, 6, 7, 5, 7]])
В результате мы получили матрицу с одной строкой, элементами которой являются все отмеченные как True элементы из исходной матрицы.
Индексация с использованием boolean выражения
Boolean выражение в Numpy можно использовать для индексации, не создавая предварительно boolean массив. Получить соответствующую выборку можно, передав в качестве индекса для объекта ndarray, условное выражение. Для иллюстрации данной возможности воспользуемся массивом nums .
>>> nums = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >>> nums[nums < 5] array([1, 2, 3, 4])
Модификация элементов ndarray с использованием boolean массивов
Еще одно возможное применение boolean массивов в Numpy – это модификация данных. В этом случае будет удобен подход индексации с использованием boolean выражения. Присвоим всем элементам из массива nums меньшим 5 значение 10, сделать это можно так.
>>> nums[nums < 5] = 10 >>> print(nums) [10 10 10 10 5 6 7 8 9 10]
Как вы можете видеть, элементы 1, 2, 3 и 4 были заменены на 10. Данных подход работает и с двумерными массивами. Покажем это на матрице m .
>>> m[m > 7] = 25 >>> print(m) [[ 1 2 3 4] [ 5 6 7 25] [25 1 5 7]]
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
Numpy. Полезные инструменты — Библиотека Numpy. Расчет статистик по данным в массиве>>>
Numpy Boolean Array – Easy Guide for Beginners
The Numpy boolean array is a type of array (collection of values) that can be used to represent logical ‘True’ or ‘False’ values stored in an array data structure in the Python programming language.
The use of a boolean array in conjunction with logic operators can be an effective way to reduce runtime computational requirements when a single logical value is needed from one or more complex variables. Boolean Arrays also find their usefulness in resultant arrays, on performing some operations.
While there may at first seem to be little use for such a construct, it is particularly important to beginners, who will often find themselves using boolean variables and arrays before they are familiar with other complex Python data types with greater flexibility.
Boolean Arrays in Python are implemented using the NumPy python library. Numpy contains a special data type called the
numpy.BooleanArray(count, dtype=bool) . This results in an array of bools(as opposed to bit integers) where the values are either 0 or 1.
Declaring a Numpy Boolean Array
A boolean array can be made using dtype=bool, manually. All values other than ‘0’, ‘False’, ‘None’, or empty strings are considered True in a boolean array.
import numpy as np arr = np.array([5, 0.001, 1, 0, 'g', None, True, False, '' "], dtype=bool) print(bool_arr) #Output: [True True True False True False True False False]
Numpy Boolean Array – Relational Operations
When relation operations are performed on the numpy boolean array, all the values are printed True where the condition matches, else other values are printed as False. Demonstrated in the below code example for equivalent operation, where values of the boolean array are checked for equal to 2.
import numpy as np A = np.array([2, 5, 7, 3, 2, 10, 2]) print(A == 2) #Output: [True False False False True False True]
Relational Operations such as: “”, “=” works as well, for computation.
The operation works for higher dimension arrays as well:
import numpy as np # a 4x3 numpy array A = np.array([[35, 67, 23, 90], [89, 101, 55, 12], [45, 2, 72, 33]]) print (A>=35) #Output: [[ True True False True] [ True True True False] [ True False True False]]
Similarly, True/False can be replaced by 0/1, using the astype() object to convert it to int type.
import numpy as np A = np.array([[90, 11, 9, 2, 34, 3, 19, 100, 41], [21, 64, 12, 65, 14, 16, 10, 122, 11], [10, 5, 12, 15, 14, 16, 10, 12, 12], [ 49, 51, 60, 75, 43, 86, 25, 22, 30]]) B = A < 20 B.astype(np.int) #Output: array([[0, 1, 1, 1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0]])
Where 0 represents False and 1 represents True in the int type.
Numpy Boolean Array – Logical Operations
Logical Operations such as: AND, OR, NOT, XOR is also operational on the boolean array with the following syntax method.
numpy.logical_and(a,b) numpy.logical_or(a,b) numpy.logical_not(a,b) # a and b are single variables or a list/array. #Output: Boolean value
Numpy Boolean Array Index
It is a property of Numpy that you can use to access specific values of an array using a boolean array. Also ready more about array indexing here.
import numpy as np # 1D Boolean indexing A = np.array([1, 2, 3])B = np.array([True, False, True]) print(A[B]) # Output: [1, 3] # 2D Boolean indexing A = np.array([4, 3, 7], [1, 2, 5]) B = np.array([True, False, True], [False, False, True]) print(A[B]) #Output: [4, 7, 5]
Conclusion
Using Numpy’s Boolean array is a simple way to make sure that the contents of your array are what you expect them to be without having to inspect each element. Hope you have learned well about numpy boolean array, how to implement it and perform operations on it.