Посчитать сколько слушателей получили 0 за вступительный экзамен numpy

Для подсчета вхождений значения в массиве numpy. Это будет работать так:

import numpy as np
a=np.array([0,3,4,3,5,4,7])
print(np.sum(a==3))

# 2

Логика заключается в том, что Булево выражение создает массив, в котором все вхождения запрошенных значений равны 1, а все остальные равны нулю. Таким образом, суммируя их, мы получим количество случаев вхождения. Это работает для массивов любой формы или типа. Не забудьте убедиться, что вы  установили пакет NumPy.

Есть два метода, которые используют для подсчета вхождения всех уникальных значений в numpy:

  • уникальный  — автоматически выравнивает многомерные массивы
  • бинарный подсчет — работает только с одномерными массивами, содержащими только положительные целые числа
unique, counts = np.unique(a, return_counts=True)
print(unique , counts) # counts[i] равняется вхождениям unique[i] в a

# [0 3 4 5 7] [1 2 2 1 1]

bin_count=np.bincount(a)
print(bin_count) # bin_count[i] равняется вхождениям i в a

# [1 0 0 2 2 1 0 1] 

Если ваши данные представляют собой массивы numpy, как правило, гораздо быстрее использовать методы numpy, чем преобразовывать данные в универсальные методы.

Подсчет всех вхождений всех элементов в итерируемом: collection.Counter

from collections import Counter
c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"])

c
# Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2})

c["a"]
# 3

c[7]  # не в списке (7 входило 0 раз!)
# 0

collections.Counter может быть использован для любого итератора и подсчитывает каждое вхождение для каждого элемента.
Примечание: Одно исключение , если dict или другой collections.Mapping -как класса дается, то он не будет считать их, а это создает счетчик с этими значениями:

Примечание: Одно исключение , если dict или другой collections.Mapping -как класса дается, то он не будет считать их, а это создает счетчик с этими значениями:

Counter({"e": 2})
# Counter({"e": 2})

Counter({"e": "e"}) # Counter не проверяет значения типа int
# Counter({"e": "e"})

Подсчет вхождений подстроки в строку: str.count

astring = 'thisisashorttext'
astring.count('t')

# 4

Это работает даже для подстрок длиннее одного символа:

astring.count('th')
# 1

astring.count('is')
# 2

astring.count('text')
# 1

которое не было бы возможно с collections.Counter, который только подсчитывает одиночные символы:

from collections import Counter
Counter(astring)

# Counter({'t': 4, 's': 3, 'h': 2,
#		   'i': 2, 'a': 1, 'o': 1,
#          'r': 1, 'e': 1, 'x': 1})

Подсчет вхождений одного элемента в последовательности: list.count() и tuple.count()

alist = [1, 2, 3, 4, 1, 2, 1, 3, 4]
alist.count(1)

# 3

atuple =('bear', 'weasel', 'bear', 'frog')
atuple.count('bear')
# 2

atuple.count('fox')
# 0 

Получение наиболее распространенного значения: collection.Counter

Подсчет ключи от Mapping не представляется возможным с collections.Counter , но мы можем посчитать значения:

from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())

# Counter({5: 3, 2: 2, 3: 1})

Наиболее распространенные элементы доступны с помощью метода most_common:

# сортируем их от наиболее распространенного 
# до наименее распространенного значения:
Counter(adict.values()).most_common()

# [(5, 3), (2, 2), (3, 1)]

# получим наиболее распространенное значение
Counter(adict.values()).most_common(1)
# [(5, 3)]

# получим 2 самых распространенных значения
Counter(adict.values()).most_common(2)
# [(5, 3), (2, 2)]

Я хочу рассчитать количество элементов в numpy.ndarry, которое больше определенного значения. Как мне получить требуемый результат?

Например:

[[0.25656927 0.31030828 0.23430803 0.25999823 0.20450112 0.19383106
  0.35779405 0.36355627 0.16837767 0.1933686  0.20630316 0.17804974
  0.06902786 0.26209944 0.21310201 0.12016498 0.14213449 0.16639964
  0.33461425 0.15897344 0.20293266 0.14630634 0.2509769  0.17211646
  0.3922994  0.14036047 0.12571093 0.25565785 0.18216616 0.0728473
  0.25328827 0.1476636  0.1873344  0.12253726 0.16082433 0.20678088
  0.33296013 0.03104548 0.14949016 0.05495472 0.1494042  0.32033417
  0.05361898 0.14325878 0.16196126 0.15796155 0.10990247 0.14499696]]

— это массив, и я хочу, чтобы количество элементов было больше 0.19214945092486838. Здесь значение будет 21. Как его посчитать?

9 ответов

Лучший ответ

Вы можете просто сделать:

import numpy

arr = numpy.asarray([0.25656927, 0.31030828, 0.23430803, 0.25999823, 0.20450112, 0.19383106, 0.35779405, 0.36355627, 0.16837767, 0.1933686,  0.20630316, 0.17804974, 0.06902786, 0.26209944, 0.21310201, 0.12016498, 0.14213449, 0.16639964, 0.33461425, 0.15897344, 0.20293266, 0.14630634, 0.2509769,  0.17211646, 0.3922994,  0.14036047, 0.12571093, 0.25565785, 0.18216616, 0.0728473, 0.25328827, 0.1476636,  0.1873344,  0.12253726, 0.16082433, 0.20678088, 0.33296013, 0.03104548, 0.14949016, 0.05495472, 0.1494042,  0.32033417, 0.05361898, 0.14325878, 0.16196126, 0.15796155, 0.10990247, 0.14499696])

print((arr > 0.19214945092486838).sum())

Результат: 21


1

lorenzozane
17 Ноя 2020 в 15:52

ar[ar>0.19214945092486838] предоставит вам список элементов, которые превышают текущие значения. Вы можете использовать len, чтобы узнать длину

>>> import numpy as np
>>> ar = np.array([0.25656927,0.31030828,0.23430803,0.25999823,0.20450112,0.19383106,0.35779405,0.36355627,0.16837767,0.1933686,0.20630316,0.17804974    ,0.06902786,0.26209944,0.21310201,0.12016498,0.14213449,0.16639964,0.33461425,0.15897344,0.20293266,0.14630634,0.2509769,0.17211646    ,0.3922994,0.14036047,0.12571093,0.25565785,0.18216616,0.0728473,0.25328827,0.1476636,0.1873344,0.12253726,0.16082433,0.20678088    ,0.33296013,0.03104548,0.14949016,0.05495472,0.1494042,0.32033417,0.05361898,0.14325878,0.16196126,0.15796155,0.10990247,0.14499696])

>>> print(len(ar[ar>0.19214945092486838]))
>>> 21


1

Edward Cullen
17 Ноя 2020 в 15:53

С помощью numpy вы можете попробовать:

Myarray= [ [ your array]]
Value_to_search=0.19214945092486838

Array_greater_than=Myarray>Value_to_search
Nb_Val_greater_than=Array_greater_than.sum()
print(Nb_Val_greater_than)


0

Renaud
17 Ноя 2020 в 15:54

Чтобы получить массив, элемент которого больше / меньше чем:

>>> import numpy as np
>>> data = np.arange(12)
>>> data > 5
array([False, False, False, False, False, False,  True,  True,  True,
        True,  True,  True])

Тогда вам просто нужно найти сумму массива:

>>> (data > 5).sum()
6

Теперь замените data своими значениями и используйте вместо него (data > 0.19214945092486838).


0

Ray
17 Ноя 2020 в 15:54

Следующий фрагмент кода позволит достичь желаемого :)

import numpy as np
arrayToCheck=np.array([0.25656927, 0.31030828, 0.23430803, 0.25999823, 0.20450112, 0.19383106,
  0.35779405, 0.36355627, 0.16837767, 0.1933686,  0.20630316, 0.17804974,
  0.06902786, 0.26209944, 0.21310201, 0.12016498, 0.14213449, 0.16639964,
  0.33461425, 0.15897344, 0.20293266, 0.14630634, 0.2509769,  0.17211646,
  0.3922994,  0.14036047, 0.12571093, 0.25565785, 0.18216616, 0.0728473,
  0.25328827, 0.1476636,  0.1873344,  0.12253726, 0.16082433, 0.20678088,
  0.33296013, 0.03104548, 0.14949016, 0.05495472, 0.1494042,  0.32033417,
  0.05361898, 0.14325878, 0.16196126, 0.15796155, 0.10990247, 0.14499696])
print ("The number of float numbers above your threshold is " + str(np.sum(a>0.19214945092486838)))


0

rodvictor
17 Ноя 2020 в 15:56

Самый чистый способ (ИМХО):

x > 1 преобразует ваш массив x в логический, где элементы больше 1 являются True. Затем вы можете подсчитать истинные значения на np.count_nonzero()

Таким образом, np.count_nonzero(x > 1)


0

Jussi Nurminen
17 Ноя 2020 в 15:56

arr=np.array([0.25656927,0.31030828,0.23430803,0.25999823,0.20450112,0.19383106,
  0.35779405, 0.36355627, 0.16837767, 0.1933686,  0.20630316, 0.17804974,
  0.06902786, 0.26209944, 0.21310201, 0.12016498, 0.14213449, 0.16639964,
  0.33461425, 0.15897344, 0.20293266, 0.14630634 ,0.2509769 , 0.17211646,
  0.3922994 , 0.14036047, 0.12571093, 0.25565785, 0.18216616, 0.0728473,
  0.25328827, 0.1476636 , 0.1873344 , 0.12253726, 0.16082433, 0.20678088,
  0.33296013, 0.03104548, 0.14949016, 0.05495472, 0.1494042 , 0.32033417,
  0.05361898, 0.14325878 ,0.16196126, 0.15796155, 0.10990247, 0.14499696])

Количество:

arr[np.where(arr>0.19214945092486838)].shape[0]
    


0

Johnson Francis
17 Ноя 2020 в 15:59

Вы можете использовать len для подсчета результатов, как в этом примере:

import numpy as np

matrix = np.array([[0.25656927,0.31030828,0.23430803,0.25999823,0.20450112,0.19383106,
  0.35779405, 0.36355627, 0.16837767, 0.1933686, 0.20630316, 0.17804974,
  0.06902786, 0.26209944, 0.21310201, 0.12016498, 0.14213449, 0.16639964,
  0.33461425, 0.15897344, 0.20293266, 0.14630634, 0.2509769,  0.17211646,
  0.3922994,  0.14036047, 0.12571093, 0.25565785, 0.18216616, 0.0728473,
  0.25328827, 0.1476636,  0.1873344,  0.12253726, 0.16082433, 0.20678088,
  0.33296013, 0.03104548, 0.14949016, 0.05495472, 0.1494042,  0.32033417,
  0.05361898, 0.14325878, 0.16196126, 0.15796155, 0.10990247, 0.14499696]])

n = len(matrix[matrix > 0.18])
print(n)


0

Jasar Orion
17 Ноя 2020 в 16:02

Вот один способ

my_array = ... the target array ...
result = sum(0.19214945092486838 < x for x in my_array)


0

Tom Barron
17 Ноя 2020 в 15:53

Библиотека Numpy предоставляет функции для расчета простых статистик: среднее значение, медиана, стандартное отклонение и т.п. Вопросу использования данных функций посвящен этот урок.

  • Введение
  • Размерность массива
  • Общие правила при работе с массивами Numpy
      • Вызов функции расчета статистики
    • Расчет статистик по строкам или столбцам массива
  • Функции (методы) для расчета статистик в Numpy

Введение

Импортируйте библиотеку Numpy, если вы еще этого не сделали.

>>> import numpy as np

Для начала создадим матрицу, которая нам понадобится в работе.

>>> 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]]

В этом случае будет создан объект типа matrix.

>>> type(m)
<class 'numpy.matrixlib.defmatrix.matrix'>

Если вы уже работали с Numpy, это может для вас быть чем-то новым. В Numpy, как правило, приходится работать с объектами класса ndarray. Мы выбрали matrix из-за удобства объявления массива, т.к. matrix позволяет использование Matlab-подобный стиль, и, наверное, вам будет интересно познакомиться с чем-то новым. Для задач, рассматриваемых в рамках данной статьи, объекты matrix и ndarray одинаково хорошо подходят. Matix можно превратить в ndarray вот так:

>>> m = np.array(m)
>>> type(m)
<class 'numpy.ndarray'>

В любом случае наша таблица чисел будет выглядеть следующим образом.

Numpy matrix

Размерность массива

Для определения размерности массива Numpy используйте атрибут shape.

>>> m.shape
(3, 4)

В результате мы получим кортеж из двух элементов, первый из них – это количество строк, второй – столбцов.

Перед тем, как перейти к описанию функций расчета статистик необходимо, чтобы вы запомнили несколько важных вещей, касательно функций и массивов Numpy.

Вызов функции расчета статистики

Для расчета той или иной статистики, соответствующую функцию можно вызвать как метод объекта, с которым вы работаете. Для нашего массива это будет выглядеть так.

>>> m.max()
9

Тот же результат можно получить вызвав библиотечную функцию с соответствующим именем, передав ей в качестве аргумента массив.

>>> np.max(m)
9

Расчет статистик по строкам или столбцам массива

Вызовем функцию вычисления статистики (максимальный элемент) без аргументов.

>>> m.max()
9

В этом случает будут обработаны все элементы массива.

Numpy max for all elements

Если необходимо найти максимальный элемент в каждой строке, то для этого нужно передать в качестве аргумента параметр axis=1.

>>> m.max(axis=1)
matrix([[4],
        [8],
        [9]])

Numpy max for rows

Для вычисления статистики по столбцам, передайте в качестве параметра аргумент axis=0.

>>> m.max(axis=0)
matrix([[9, 6, 7, 8]])

Numpy max for cols

Функции (методы) для расчета статистик в Numpy

Ниже, в таблице, приведены методы объекта ndarray (или matrix), которые, как мы помним из раздела выше, могут быть также вызваны как функции библиотеки Numpy, для расчета статистик по данным массива.

Имя метода Описание
argmax Индексы элементов с максимальным значением (по осям)
argmin Индексы элементов с минимальным значением (по осям)
max Максимальные значения элементов (по осям)
min Минимальные значения элементов (по осям)
mean Средние значения элементов (по осям)
prod Произведение всех элементов (по осям)
std Стандартное отклонение (по осям)
sum Сумма всех элементов (по осям)
var Дисперсия (по осям)

Вычислим некоторые из представленных выше статистик.

>>> m.mean()
4.833333333333333
>>> m.mean(axis=1)
matrix([[2.5],
        [6.5],
        [5.5]])
>>> m.sum()
58
>>> m.sum(axis=0)
matrix([[15,  9, 15, 19]])

P.S.

Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
Книга: Pandas. Работа с данными
<<<Библиотека Numpy. Использование boolean массива для доступа к ndarray — Библиотека numpy. Работа с массивами. Слайсы>>>

In this post, we are going to learn NumPy count zero values with examples. We will learn how to count zero in each row or column of a numpy array by using np. where(), np.count_nonzero(),np.sum(), np.bincount()

1.NumPy count zero in whole array


To count all zero values in the NumPy array we have three NumPy functions that we are going to understand with examples one by one that can be used with 1D,2D, and Multidimensional arrays.

  • np.count_nonzero()
  • np.where()
  • np.sum()
  • np.bincount()

1.1 np.count_nonzero() to count All zero values in array


The count_nonzero() returns the count of elements of the numpy array for a condition that returns True. Where True is equal to 1 or False is equal is 0. If we do not pass the axis in count_nonzero() returns the count of all zero values in the numpy array.

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])
print('Total zero in Whole array  :',np.count_nonzero(nparr==0))

Output

Total zero in Whole array  : 5

Frequently Asked Questions

  • NumPy count elements by condition
  • Numpy count Frequency of value
  • NumPy 2D array count unique value occurrence
  • How to count non-nan elements in NumPy array
  • NumPy count zero values (4 methods)

1.2 NumPy.sum() to count all zero values in array


The np. sum() function returns the sum of elements over the specified axis of an array default value for the axis is None. If the axis is not specified the sum() function count of all Zero values in the whole NumPy array is returned.

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])
print('np.sum() : Total zero in Whole array  :',np.sum(nparr==0))

Output

np.sum() : Total zero in Whole array : 5

1.3 Numpy count all zero using np.where()


In this python program example, we are using the numpy the where() function to count the zero values in NumPy 2D array bypassing the condition nparr==0

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])

result = np.where(nparr==0)
print(result)
zero_inArr = result[0].size

print('Total zero in Whole array  :',zero_inArr)

Output

Total zero in Whole array  : 5

1.4 bincount() to count all zero in a 1D numpy array


In this Python program, we have used np. bincount() function to count all zero values in 1D numpy array

import numpy as np
nparr =  np.array([3, 6, 9, 0, 0, 0, 12, 0,15,28,0,27])

zerocount = np.bincount(nparr)
print('NumPy all zero vales in 1D array:',zerocount[0])

Output

NumPy all zero vales in 1D array: 5

2. NumPy count zero values in each row using count_nonzero()


To count elements rows and columns wise we pass the axis as we are in the below programs.

  • To count zeros values in each row of a 2D array We pass argument axis=1 in the count_nonzero() function.
import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])
print('np.count_nonzero(): count zero in each row :',np.count_nonzero(nparr==0,axis=1))

Output

np.count_nonzero(): count zero in each row : [1 3 1]

3. NumPy count zero values in each row using np.sum()


To count zeros values in each row of a 2D array ,We pass argument axis=1 in the np.sum() function.Let us understand with the below python program.

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])

print('np.sum(): count zero in each row :',np.sum(nparr==0,axis =1))

Output

np.sum(): count zero in each row : [1 3 1]

4. NumPy count zero values in each column using np.count_nonzero()


In the case of the multidimensional array To count Zero values in each column of the 2D array we pass argument axis=0.Let us understand how to count zero in each column of a numpy 2D array.

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])


print('np.count_nonzero(): count zero in each column :',np.count_nonzero(nparr==0,axis=0))

Output

np.count_nonzero(): count zero in each column : [1 1 1 2]

5. NumPy count zero in each column using np. sum()


In this Python program, we are counting zero values in each column of the numpy array using the np.sum() function by setting the axis=0 values in the whole array.Install and Import the Numpy library using “import numpy as np”

import numpy as np
nparr =  np.array([[3, 6, 9, 0],
                   [ 0, 0, 12, 0],
                   [15,28,0,27]])
print('np.sum(): count zero in each column :',np.sum(nparr==0,axis =0))

Output

np.sum(): count zero in each column : [1 1 1 2]

A 2x faster approach would be to just use np.count_nonzero() but with the condition as needed.

In [3]: arr
Out[3]: 
array([[1, 2, 0, 3],
      [3, 9, 0, 4]])

In [4]: np.count_nonzero(arr==0)
Out[4]: 2

In [5]:def func_cnt():
            for arr in arrs:
                zero_els = np.count_nonzero(arr==0)
                # here, it counts the frequency of zeroes actually

You can also use np.where() but it’s slower than np.count_nonzero()

In [6]: np.where( arr == 0)
Out[6]: (array([0, 1]), array([2, 2]))

In [7]: len(np.where( arr == 0))
Out[7]: 2

Efficiency: (in descending order)

In [8]: %timeit func_cnt()
10 loops, best of 3: 29.2 ms per loop

In [9]: %timeit func1()
10 loops, best of 3: 46.5 ms per loop

In [10]: %timeit func_where()
10 loops, best of 3: 61.2 ms per loop

more speedups with accelerators

It is now possible to achieve more than 3 orders of magnitude speed boost with the help of JAX if you’ve access to accelerators (GPU/TPU). Another advantage of using JAX is that the NumPy code needs very little modification to make it JAX compatible. Below is a reproducible example:

In [1]: import jax.numpy as jnp
In [2]: from jax import jit

# set up inputs
In [3]: arrs = []
In [4]: for _ in range(1000):
   ...:     arrs.append(np.random.randint(-5, 5, 10000))

# JIT'd function that performs the counting task
In [5]: @jit
   ...: def func_cnt():
   ...:     for arr in arrs:
   ...:         zero_els = jnp.count_nonzero(arr==0)

# efficiency test
In [8]: %timeit func_cnt()
15.6 µs ± 391 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

  • Импортировать NumPy под именем np

  • Напечатать версию и конфигурацию

    print(np.__version__)
    np.show_config()
  • Создать вектор (одномерный массив) размера 10, заполненный нулями

    Z = np.zeros(10)
    print(Z)
  • Создать вектор размера 10, заполненный единицами

  • Создать вектор размера 10, заполненный числом 2.5

    Z = np.full(10, 2.5)
    print(Z)
  • Как получить документацию о функции numpy.add из командной строки?

    python3 -c "import numpy; numpy.info(numpy.add)"
  • Создать вектор размера 10, заполненный нулями, но пятый элемент равен 1

    Z = np.zeros(10)
    Z[4] = 1
    print(Z)
  • Создать вектор со значениями от 10 до 49

    Z = np.arange(10,50)
    print(Z)
  • Развернуть вектор (первый становится последним)

    Z = np.arange(50)
    Z = Z[::-1]
  • Создать матрицу (двумерный массив) 3×3 со значениями от 0 до 8

    Z = np.arange(9).reshape(3,3)
    print(Z)
  • Найти индексы ненулевых элементов в [1,2,0,0,4,0]

    nz = np.nonzero([1,2,0,0,4,0])
    print(nz)
  • Создать 3×3 единичную матрицу

  • Создать массив 3x3x3 со случайными значениями

    Z = np.random.random((3,3,3))
    print(Z)
  • Создать массив 10×10 со случайными значениями, найти минимум и максимум

    Z = np.random.random((10,10))
    Zmin, Zmax = Z.min(), Z.max()
    print(Zmin, Zmax)
  • Создать случайный вектор размера 30 и найти среднее значение всех элементов

    Z = np.random.random(30)
    m = Z.mean()
    print(m)
  • Создать матрицу с 0 внутри, и 1 на границах

    Z = np.ones((10,10))
    Z[1:-1,1:-1] = 0
  • Выяснить результат следующих выражений

    0 * np.nan
    np.nan == np.nan
    np.inf > np.nan
    np.nan - np.nan
    0.3 == 3 * 0.1
  • Создать 5×5 матрицу с 1,2,3,4 под диагональю

    Z = np.diag(np.arange(1, 5), k=-1)
    print(Z)
  • Создать 8×8 матрицу и заполнить её в шахматном порядке

    Z = np.zeros((8,8), dtype=int)
    Z[1::2,::2] = 1
    Z[::2,1::2] = 1
    print(Z)
  • Дан массив размерности (6,7,8). Каков индекс (x,y,z) сотого элемента?

    print(np.unravel_index(100, (6,7,8)))
  • Создать 8×8 матрицу и заполнить её в шахматном порядке, используя функцию tile

    Z = np.tile(np.array([[0,1],[1,0]]), (4,4))
    print(Z)
  • Перемножить матрицы 5×3 и 3×2

    Z = np.dot(np.ones((5,3)), np.ones((3,2)))
    print(Z)
  • Дан массив, поменять знак у элементов, значения которых между 3 и 8

    Z = np.arange(11)
    Z[(3 < Z) & (Z <= 8)] *= -1
  • Создать 5×5 матрицу со значениями в строках от 0 до 4

    Z = np.zeros((5,5))
    Z += np.arange(5)
    print(Z)
  • Есть генератор, сделать с его помощью массив

    def generate():
        for x in xrange(10):
            yield x
    Z = np.fromiter(generate(),dtype=float,count=-1)
    print(Z)
  • Создать вектор размера 10 со значениями от 0 до 1, не включая ни то, ни другое

    Z = np.linspace(0,1,12)[1:-1]
    print(Z)
  • Отсортировать вектор

    Z = np.random.random(10)
    Z.sort()
    print(Z)
  • Проверить, одинаковы ли 2 numpy массива

    A = np.random.randint(0,2,5)
    B = np.random.randint(0,2,5)
    equal = np.allclose(A,B)
    print(equal)
  • Сделать массив неизменяемым

    Z = np.zeros(10)
    Z.flags.writeable = False
    Z[0] = 1
  • Дан массив 10×2 (точки в декартовой системе координат), преобразовать в полярную

    Z = np.random.random((10,2))
    X,Y = Z[:,0], Z[:,1]
    R = np.hypot(X, Y)
    T = np.arctan2(Y,X)
    print(R)
    print(T)
  • Заменить максимальный элемент на ноль

    Z = np.random.random(10)
    Z[Z.argmax()] = 0
    print(Z)
  • Создать структурированный массив с координатами x, y на сетке в квадрате [0,1]x[0,1]

    Z = np.zeros((10,10), [('x',float),('y',float)])
    Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10),
                                 np.linspace(0,1,10))
    print(Z)
  • Из двух массивов сделать матрицу Коши C (Cij = 1/(xi — yj))

    X = np.arange(8)
    Y = X + 0.5
    C = 1.0 / np.subtract.outer(X, Y)
    print(np.linalg.det(C))
  • Найти минимальное и максимальное значение, принимаемое каждым числовым типом numpy

    for dtype in [np.int8, np.int32, np.int64]:
       print(np.iinfo(dtype).min)
       print(np.iinfo(dtype).max)
    for dtype in [np.float32, np.float64]:
       print(np.finfo(dtype).min)
       print(np.finfo(dtype).max)
       print(np.finfo(dtype).eps)
  • Напечатать все значения в массиве

    np.set_printoptions(threshold=np.nan)
    Z = np.zeros((25,25))
    print(Z)
  • Найти ближайшее к заданному значению число в заданном массиве

    Z = np.arange(100)
    v = np.random.uniform(0,100)
    index = (np.abs(Z-v)).argmin()
    print(Z[index])
  • Создать структурированный массив, представляющий координату (x,y) и цвет (r,g,b)

     Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                       ('y', float, 1)]),
                        ('color',    [ ('r', float, 1),
                                       ('g', float, 1),
                                       ('b', float, 1)])])
    print(Z)
  • Дан массив (100,2) координат, найти расстояние от каждой точки до каждой

    import scipy.spatial
    
    Z = np.random.random((10,2))
    D = scipy.spatial.distance.cdist(Z,Z)
    print(D)
  • Преобразовать массив из float в int

    Z = np.arange(10, dtype=np.int32)
    Z = Z.astype(np.float32, copy=False)
  • Дан файл:

    1,2,3,4,5
    6,,,7,8
    ,,9,10,11
    

    Как прочитать его?

    Z = np.genfromtxt("missing.dat", delimiter=",")
  • Каков эквивалент функции enumerate для numpy массивов?

    Z = np.arange(9).reshape(3,3)
    for index, value in np.ndenumerate(Z):
        print(index, value)
    for index in np.ndindex(Z.shape):
        print(index, Z[index])
  • Сформировать 2D массив с распределением Гаусса

    X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
    D = np.hypot(X, Y)
    sigma, mu = 1.0, 0.0
    G = np.exp(-((D - mu) ** 2 / (2.0 * sigma ** 2)))
    print(G)
  • Случайно расположить p элементов в 2D массив

    n = 10
    p = 3
    Z = np.zeros((n,n))
    np.put(Z, np.random.choice(range(n*n), p, replace=False), 1)
  • Отнять среднее из каждой строки в матрице

    X = np.random.rand(5, 10)
    Y = X - X.mean(axis=1, keepdims=True)
  • Отсортировать матрицу по n-ому столбцу

    Z = np.random.randint(0,10,(3,3))
    n = 1  # Нумерация с нуля
    print(Z)
    print(Z[Z[:,n].argsort()])
  • Определить, есть ли в 2D массиве нулевые столбцы

    Z = np.random.randint(0,3,(3,10))
    print((~Z.any(axis=0)).any())
  • Дан массив, добавить 1 к каждому элементу с индексом, заданным в другом массиве (осторожно с повторами)

    Z = np.ones(10)
    I = np.random.randint(0,len(Z),20)
    Z += np.bincount(I, minlength=len(Z))
    print(Z)
  • Дан массив (w,h,3) (картинка) dtype=ubyte, посчитать количество различных цветов

    w,h = 16,16
    I = np.random.randint(0, 2, (h,w,3)).astype(np.ubyte)
    F = I[...,0] * 256 * 256 + I[...,1] * 256 + I[...,2]
    n = len(np.unique(F))
    print(np.unique(I))
  • Дан четырехмерный массив, посчитать сумму по последним двум осям

    A = np.random.randint(0,10, (3,4,3,4))
    sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
    print(sum)
  • Найти диагональные элементы произведения матриц

    # Slow version
    np.diag(np.dot(A, B))
    
    # Fast version
    np.sum(A * B.T, axis=1)
    
    # Faster version
    np.einsum("ij,ji->i", A, B).
  • Дан вектор [1, 2, 3, 4, 5], построить новый вектор с тремя нулями между каждым значением

    Z = np.array([1,2,3,4,5])
    nz = 3
    Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
    Z0[::nz+1] = Z
    print(Z0)
  • Поменять 2 строки в матрице

    A = np.arange(25).reshape(5,5)
    A[[0,1]] = A[[1,0]]
    print(A)
  • Рассмотрим набор из 10 троек, описывающих 10 треугольников (с общими вершинами), найти множество уникальных отрезков, составляющих все треугольники

    faces = np.random.randint(0,100,(10,3))
    F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
    F = F.reshape(len(F)*3,2)
    F = np.sort(F,axis=1)
    G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
    G = np.unique(G)
    print(G)
  • Дан массив C; создать массив A, что np.bincount(A) == C

    C = np.bincount([1,1,2,3,4,4,6])
    A = np.repeat(np.arange(len(C)), C)
    print(A)
  • Посчитать среднее, используя плавающее окно

    def moving_average(a, n=3):
        ret = np.cumsum(a, dtype=float)
        ret[n:] = ret[n:] - ret[:-n]
        return ret[n - 1:] / n
    
    print(moving_average(np.arange(20), 3))
  • Дан вектор Z, построить матрицу, первая строка которой (Z[0],Z[1],Z[2]), каждая последующая сдвинута на 1 (последняя (Z[-3],Z[-2],Z[-1]))

    from numpy.lib import stride_tricks
    
    def rolling(a, window):
        shape = (a.size - window + 1, window)
        strides = (a.itemsize, a.itemsize)
        return stride_tricks.as_strided(a, shape=shape, strides=strides)
    Z = rolling(np.arange(10), 3)
    print(Z)
  • Инвертировать булево значение, или поменять знак у числового массива без создания нового

    Z = np.random.randint(0,2,100)
    np.logical_not(arr, out=arr)
    
    Z = np.random.uniform(-1.0,1.0,100)
    np.negative(arr, out=arr)
  • Рассмотрим 2 набора точек P0, P1 описания линии (2D) и точку р, как вычислить расстояние от р до каждой линии i (P0[i],P1[i])

    def distance(P0, P1, p):
        T = P1 - P0
        L = (T**2).sum(axis=1)
        U = -((P0[:,0] - p[...,0]) * T[:,0] + (P0[:,1] - p[...,1]) * T[:,1]) / L
        U = U.reshape(len(U),1)
        D = P0 + U * T - p
        return np.sqrt((D**2).sum(axis=1))
    
    P0 = np.random.uniform(-10,10,(10,2))
    P1 = np.random.uniform(-10,10,(10,2))
    p  = np.random.uniform(-10,10,( 1,2))
    print(distance(P0, P1, p))
  • Дан массив. Написать функцию, выделяющую часть массива фиксированного размера с центром в данном элементе (дополненное значением fill если необходимо)

    Z = np.random.randint(0,10, (10,10))
    shape = (5,5)
    fill  = 0
    position = (1,1)
    
    R = np.ones(shape, dtype=Z.dtype)*fill
    P  = np.array(list(position)).astype(int)
    Rs = np.array(list(R.shape)).astype(int)
    Zs = np.array(list(Z.shape)).astype(int)
    
    R_start = np.zeros((len(shape),)).astype(int)
    R_stop  = np.array(list(shape)).astype(int)
    Z_start = (P - Rs//2)
    Z_stop  = (P + Rs//2)+Rs%2
    
    R_start = (R_start - np.minimum(Z_start, 0)).tolist()
    Z_start = (np.maximum(Z_start, 0)).tolist()
    R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
    Z_stop = (np.minimum(Z_stop,Zs)).tolist()
    
    r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
    z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
    R[r] = Z[z]
    print(Z)
    print(R)
  • Посчитать ранг матрицы

    Z = np.random.uniform(0,1,(10,10))
    rank = np.linalg.matrix_rank(Z)
  • Найти наиболее частое значение в массиве

    Z = np.random.randint(0,10,50)
    print(np.bincount(Z).argmax())
  • Извлечь все смежные 3×3 блоки из 10×10 матрицы

    Z = np.random.randint(0,5,(10,10))
    n = 3
    i = 1 + (Z.shape[0] - n)
    j = 1 + (Z.shape[1] - n)
    C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
    print(C)
  • Создать подкласс симметричных 2D массивов (Z[i,j] == Z[j,i])

    # Note: only works for 2d array and value setting using indices
    
    class Symetric(np.ndarray):
        def __setitem__(self, (i,j), value):
            super(Symetric, self).__setitem__((i,j), value)
            super(Symetric, self).__setitem__((j,i), value)
    
    def symetric(Z):
        return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
    
    S = symetric(np.random.randint(0,10,(5,5)))
    S[2,3] = 42
    print(S)
  • Рассмотрим множество матриц (n,n) и множество из p векторов (n,1). Посчитать сумму p произведений матриц (результат имеет размерность (n,1))

    p, n = 10, 20
    M = np.ones((p,n,n))
    V = np.ones((p,n,1))
    S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
    print(S)
    
    # It works, because:
    # M is (p,n,n)
    # V is (p,n,1)
    # Thus, summing over the paired axes 0 and 0 (of M and V independently),
    # and 2 and 1, to remain with a (n,1) vector.
  • Дан массив 16×16, посчитать сумму по блокам 4×4

    Z = np.ones((16,16))
    k = 4
    S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
                                           np.arange(0, Z.shape[1], k), axis=1)
  • Написать игру «жизнь»

    def iterate(Z):
        # Count neighbours
        N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
             Z[1:-1,0:-2]                + Z[1:-1,2:] +
             Z[2:  ,0:-2] + Z[2:  ,1:-1] + Z[2:  ,2:])
    
        # Apply rules
        birth = (N == 3) & (Z[1:-1,1:-1]==0)
        survive = ((N == 2) | (N == 3)) & (Z[1:-1,1:-1] == 1)
        Z[...] = 0
        Z[1:-1,1:-1][birth | survive] = 1
        return Z
    
    Z = np.random.randint(0,2,(50,50))
    for i in range(100):
        print(Z)
        Z = iterate(Z)
  • Найти n наибольших значений в массиве

    Z = np.arange(10000)
    np.random.shuffle(Z)
    n = 5
    
    print (Z[np.argpartition(-Z,n)[:n]])
  • Построить прямое произведение массивов (все комбинации с каждым элементом)

    def cartesian(arrays):
        arrays = [np.asarray(a) for a in arrays]
        shape = map(len, arrays)
    
        ix = np.indices(shape, dtype=int)
        ix = ix.reshape(len(arrays), -1).T
    
        for n, arr in enumerate(arrays):
            ix[:, n] = arrays[n][ix[:, n]]
    
        return ix
    
    print(cartesian(([1, 2, 3], [4, 5], [6, 7])))
  • Даны 2 массива A (8×3) и B (2×2). Найти строки в A, которые содержат элементы из каждой строки в B, независимо от порядка элементов в B

    A = np.random.randint(0,5,(8,3))
    B = np.random.randint(0,5,(2,2))
    
    C = (A[..., np.newaxis, np.newaxis] == B)
    rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0]
    print(rows)
  • Дана 10×3 матрица, найти строки из неравных значений (например [2,2,3])

    Z = np.random.randint(0,5,(10,3))
    E = np.logical_and.reduce(Z[:,1:] == Z[:,:-1], axis=1)
    U = Z[~E]
    print(Z)
    print(U)
  • Преобразовать вектор чисел в матрицу бинарных представлений

    I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
    print(np.unpackbits(I[:, np.newaxis], axis=1))
  • Дан двумерный массив. Найти все различные строки

    Z = np.random.randint(0, 2, (6,3))
    T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
    _, idx = np.unique(T, return_index=True)
    uZ = Z[idx]
    print(uZ)
  • Даны векторы A и B, написать einsum эквиваленты функций inner, outer, sum и mul

    # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
    
    np.einsum('i->', A)       # np.sum(A)
    np.einsum('i,i->i', A, B) # A * B
    np.einsum('i,i', A, B)    # np.inner(A, B)
    np.einsum('i,j', A, B)    # np.outer(A, B)
  • In this tutorial, we will look at how to count zeros in a numpy array. We will also look at how to count zeros present in each row and each column of a 2d array.

    You can use np.count_nonzero() or the np.where() functions to count zeros in a numpy array. In fact, you can use these functions to count values satisfying any given condition (for example, whether they are zero or not, or whether they are greater than some value or not, etc).

    Note that using np.count_nonzero() is simpler of the two methods. The following is the syntax to count zeros using this function –

    # arr is a numpy array
    # count of zeros in arr 
    n_zeros = np.count_nonzero(arr==0)

    Let’s look at some examples of how to use the above functions. First, we will create a couple of numpy arrays that we will be using throughout this tutorial.

    import numpy as np
    
    # one-dimensional array
    arr_1d = np.array([3, 0, 5, 2, 1, 0, 8, 6])
    print(arr_1d)
    
    # two-dimensional array
    arr_2d = np.array([[4, 3, 0],
                       [0, 0, 2],
                       [2, 5, 6]])
    print(arr_2d)

    Output:

    [3 0 5 2 1 0 8 6]
    [[4 3 0]
     [0 0 2]
     [2 5 6]]

    Now we have a one-dimensional array and a two-dimensional array for which we will be counting the zeros.

    Count all zeros in the array

    To count all the zeros in an array, simply use the np.count_nonzero() function checking for zeros. It returns the count of elements inside the array satisfying the condition (in this case, if it’s zero or not).

    Let’s use this function to count the zeros in arr_1d created above:

    # count zeros in 1d array
    n_zeros = np.count_nonzero(arr_1d==0)
    # display the count of zeros
    print(n_zeros)

    Output:

    2

    We get 2 as the output since there are two zero elements in the 1d array arr_1d.

    You can also use the same syntax to count zeros in higher dimensional arrays. Let’s count the number of zeros in arr_2d using np.count_nonzero()

    # count zeros in 2d array
    n_zeros = np.count_nonzero(arr_2d==0)
    # display the count of zeros
    print(n_zeros)

    Output:

    3

    We get 3 as the output since there are three zero value elements in the array arr_2d.

    Count of zeros in each row

    To count zeros in each row, pass axis=1 to the np.count_nonzero() function. Let’s count zeros in each row of arr_2d

    # count zeros in each row
    n_zeros = np.count_nonzero(arr_2d==0, axis=1)
    # display the count of zeros
    print(n_zeros)

    Output:

    [1 2 0]

    It returns a numpy array of the count of zeros in each row. You can see that we have one zero-element in the first row, two in the second row, and no such elements in the third row.

    Count of zeros in each column

    To count zeros in each column, pass axis=0 to the np.count_nonzero() function. Let’s count the zeros in each column of arr_2d

    # count zeros in each column
    n_zeros = np.count_nonzero(arr_2d==0, axis=0)
    # display the count of zeros
    print(n_zeros)

    Output:

    [1 1 1]

    We have one zero-element in each column of the array arr_2d.

    For more on the np.count_nonzero() function, refer to its documentation.

    Using np.where() to count zeros in an array

    Alternatively, you can use np.where() to count the zeros in an array. np.where() is generally used to find indexes of elements satisfying a condition in a numpy array.

    You can use this function to find indexes of zero-valued elements in the array and then count them to get the count of zeros in the array. Let’s count the zeros in the array arr_1d using this method:

    # count zeros with np.where
    result = np.where(arr_1d==0)
    # show the result of np.where
    print(result)
    
    # count of zeros
    n_zeros = result[0].size
    # display the count of zeros
    print(n_zeros)

    Output:

    (array([1, 5], dtype=int64),)
    2

    You can see that np.where() results in a tuple of numpy arrays showing the indexes satisfying the condition. We see that zeros are present at index 1 and 5 in the array arr_1. To get the count, we use the .size attribute of this index array.

    You can also use np.where() to count zeros in higher-dimensional arrays as well. For example, let’s use it to count zeros in arr_2d

    # count zeros with np.where
    result = np.where(arr_2==0)
    # show the result of np.where
    print(result)
    
    # count of zeros
    n_zeros = result[0].size
    # display the count of zeros
    print(n_zeros)

    Output:

    (array([0, 1, 1], dtype=int64), array([2, 0, 1], dtype=int64))
    3

    The returned value from np.where() is a tuple of two arrays, the first one shows the row indexes of elements matching the condition (element equal to zero) and the second array gives the column indexes for those elements. Counting the indexes in any of these arrays gives the count of zeros in the array.

    With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

    Subscribe to our newsletter for more informative guides and tutorials.
    We do not spam and you can opt out any time.

    Tutorials on numpy arrays –

    • How to sort a Numpy Array?
    • Create Pandas DataFrame from a Numpy Array
    • Different ways to Create NumPy Arrays
    • Convert Numpy array to a List – With Examples
    • Append Values to a Numpy Array
    • Find Index of Element in Numpy Array
    • Read CSV file as NumPy Array
    • Filter a Numpy Array – With Examples
    • Python – Randomly select value from a list
    • Numpy – Sum of Values in Array
    • Numpy – Elementwise sum of two arrays
    • Numpy – Elementwise multiplication of two arrays
    • Using the numpy linspace() method
    • Using numpy vstack() to vertically stack arrays
    • Numpy logspace() – Usage and Examples
    • Using the numpy arange() method
    • Using numpy hstack() to horizontally stack arrays
    • Trim zeros from a numpy array in Python
    • Get unique values and counts in a numpy array
    • Horizontally split numpy array with hsplit()
    • Piyush Raj

      Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

      View all posts

    Понравилась статья? Поделить с друзьями:
  • Посчитать количество баллов егэ профильная математика
  • Поурочные разработки по русскому языку 4 класс канакина издательство экзамен
  • Посчитать количество баллов егэ онлайн
  • Потчевать услужливый раскашлялся берестяные грамоты письмецо удостоившись егэ
  • Посчитать вторичный балл егэ онлайн