- Как подсчитать количество вхождений элементов в NumPy
- Пример 1. Подсчет вхождений определенного значения
- Пример 2. Подсчет вхождений значений, удовлетворяющих одному условию
- Пример 3. Подсчет вхождений значений, удовлетворяющих одному из нескольких условий
- Дополнительные ресурсы
- Numpy Count | Practical Explanation of Occurrence Finder
- What is Numpy Count?
- Syntax of Numpy Count
- Parameters of Numpy Count
- arr : array
- substring
- start / end
- Return Value
- Examples of Numpy Count
- Str.count vs Numpy Count
- numpy.count_nonzero
- What’s Next?
- Conclusion
- Python NumPy Array: How to Count Elements - Top 8 Methods
- Counting True elements in NumPy array
- Counting occurrences of values in NumPy array
- Finding the total number of elements in an array
- Counting occurrences of a character in a string or an array
- Using len() function to count the number of elements in an array
- Counting non-masked elements of an array along a given axis
- Counting the number of occurrences of each value in an array
- Counting non-masked elements of an array along a given axis
- Other simple code examples for counting elements in a NumPy array with Python
- Conclusion
Как подсчитать количество вхождений элементов в NumPy
Вы можете использовать следующие методы для подсчета вхождений элементов в массиве NumPy:
Метод 1: подсчет вхождений определенного значения
Метод 2: подсчет вхождений значений, удовлетворяющих одному условию
Метод 3: подсчет вхождений значений, удовлетворяющих одному из нескольких условий
np.count_nonzero ((x == 2 ) | (x == 7 ))
В следующих примерах показано, как использовать каждый метод на практике со следующим массивом NumPy:
import numpy as np #create NumPy array x = np.array([2, 2, 2, 4, 5, 5, 5, 7, 8, 8, 10, 12])
Пример 1. Подсчет вхождений определенного значения
В следующем коде показано, как подсчитать количество элементов в массиве NumPy, равных значению 2:
#count number of values in array equal to 2 np.count_nonzero (x == 2 ) 3
Из вывода мы видим, что 3 значения в массиве NumPy равны 2.
Пример 2. Подсчет вхождений значений, удовлетворяющих одному условию
В следующем коде показано, как подсчитать количество элементов в массиве NumPy, значение которых меньше 6:
#count number of values in array that are less than 6 np.count_nonzero (x < 6 ) 7
Из вывода мы видим, что 7 значений в массиве NumPy имеют значение меньше 6.
Пример 3. Подсчет вхождений значений, удовлетворяющих одному из нескольких условий
В следующем коде показано, как подсчитать количество элементов в массиве NumPy, равных 2 или 7:
#count number of values in array that are equal to 2 *or* 7 np.count_nonzero ((x == 2 ) | (x == 7 )) 4
Из вывода мы видим, что 4 значения в массиве NumPy равны 2 или 7.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в Python:
Numpy Count | Practical Explanation of Occurrence Finder
Numpy one of the best and most widely used modules.Because it makes the computation easy and simple with faster speed. Similarly, we have a numpy count, a method to find a substring occurrence in a given array or list. This is easy to use, and simple is working. But like Numpy, the behind the scenes things are complex.
What is Numpy Count?
The actual function is num.char.count(). So the syntax changes a little. But function work remains the same: to find the count of occurrence of a particular string. That, too, from a given list of words without overlapping the occurrence in each word of the list.
Syntax of Numpy Count
The following is the syntax of using numpy count function:
numpy.core.defchararray.count(arr, substring, start=0, end=None)
While the usual way of writing it is :
np.char.count(array, substring)
Parameters of Numpy Count
Parameter | Mandatory or Not |
arr | Mandatory |
substring | Mandatory |
start | optional |
end | optional |
arr : array
arr or (array) is the base of our function. Because this parameter provides the list of strings. While it is a ndarray, it is easily traversed by function. And the count is done for each string separately. The data type used is either array-like or string only.
substring
substring tells the combination of the characters to be searched in the array provided. That is to say, it is mandatory to be used. The function considers all the characters as one. So it becomes easier to traverse and count. The data type used should be str or Unicode.
start / end
They define the boundaries of search. Because they are the positions of search in a string. They are optional to use and usually not used. They have an int data type. Start and end both are used individually as per the demand. While the position by the end is not included, the start is included. The limits they make are for each string irrespective of others.
Return Value
As per the numpy.org, This function returns an array. That contains the number of non-overlapping occurrences of substring sub in the range [start, end]. In other words, An integer array with the number of non-overlapping occurrences of the substring.
Examples of Numpy Count
Before we start coding we need to import the module – numpy:
Now we are ready to code. So we create an array:
arr = np.array(['ahhert','bhherta','hhertab','jhahhertb']) arr array(['ahhert', 'bahherta', 'hhertab', 'jhahhertb'], dtype='Now we use the function on it:
np.char.count(arr,'hhe') array([1, 1, 1, 1]) np.char.count(arr,'ab') array([0, 0, 1, 0])Here, we searched two different substrings without defining limits. And the result shows the working. There are four strings and in each, we have ‘hhe’ only once. While there were more ‘h’ it only considered the combined ones. The same goes for the second example, ‘ab’ occur together twice. But only once is ‘b’ after ‘a’.
np.char.count(arr,'h',2) array([1, 2, 0, 2]) np.char.count(arr,'b',start=2) array([0, 0, 1, 1]) np.char.count(arr,'a',end=4) array([1, 0, 0, 1]) np.char.count(arr,'a',3,7) array([0, 0, 1, 0]) np.char.count(arr,'h',start=3,end=6) array([0, 1, 0, 2])Here, you can see the start and end can be used individually. And even without using the word start and end, we can assign positions.
Str.count vs Numpy Count
The count is used in one more way in basic python as string.count(). As per W3schools, The method returns the number of times a specified value appears in the string. That is similar to numpy count but a little different.
arr.count('hh') Traceback (most recent call last): File "", line 1, in AttributeError: 'numpy.ndarray' object has no attribute 'count' a = ' i love to play football' a.count('pla') 1 a.count('o') 4If we use count directly it gives a traceback error. Because ‘arr’ is an N-dimensional array with multiple string array. While if we use a simple string like ‘a’, it gives similar results. So in numpy count function is called for each string separately and rest is same
numpy.count_nonzero
When you search for numpy count, you may get this function as well. This Counts the number of non-zero values in the array a . With the syntax: numpy.count_nonzero (a, axis=None, *, keepdims=False)
It counts the number of nonzero values in an N-dimensional array. Without an axis, it tells for the whole array. With axis, it tells results as a row or column.
What’s Next?
NumPy is very powerful and incredibly essential for information science in Python. That being true, if you are interested in data science in Python, you really ought to find out more about Python.
You might like our following tutorials on numpy.
Conclusion
In conclusion, we can say that numpy count is commonly used and easily understood. So everyone can use it with comfort and make the computation easier.
Still have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!
Python NumPy Array: How to Count Elements - Top 8 Methods
Learn how to count elements in a NumPy array in Python with these 8 powerful methods. From counting True elements to finding the total number of elements, this blog post covers it all.
- Counting True elements in NumPy array
- Counting occurrences of values in NumPy array
- Finding the total number of elements in an array
- Counting occurrences of a character in a string or an array
- Using len() function to count the number of elements in an array
- Counting non-masked elements of an array along a given axis
- Counting the number of occurrences of each value in an array
- Counting non-masked elements of an array along a given axis
- Other simple code examples for counting elements in a NumPy array with Python
- Conclusion
- How do you count specific elements in an array in Python?
- How do you count elements in an array?
- Is there a count function in NumPy?
In Python, NumPy is a powerful library for numerical computing. It provides a powerful array object that can be used for various mathematical operations. Counting the number of elements in a numpy array is one of the basic operations carried out in scientific computing. Python provides various methods to count the number of elements in a NumPy array. In this blog post, we will discuss the top 8 methods to count the number of elements in a NumPy array in Python.
Counting True elements in NumPy array
The np.count_nonzero() function can be used to count the number of True elements in a NumPy array. It returns the number of non-zero elements in the input array. The function can also be used to count the number of non-zero elements along a specified axis. Here’s an example code snippet:
import numpy as nparr = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 1]]) count = np.count_nonzero(arr) print(count)
Counting occurrences of values in NumPy array
The numpy.bincount() function can be used to count the number of occurrences of each value in an array of non-negative integers. It returns an array of length max(input_array) + 1 , where the i-th element is the number of occurrences of the i-th value in the input array. Here’s an example code snippet:
import numpy as nparr = np.array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0]) counts = np.bincount(arr) print(counts)
Finding the total number of elements in an array
The numpy.ndarray.size() function can be used to find the total number of elements in an array. It returns the total number of elements in the input array. Here’s an example code snippet:
import numpy as nparr = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 1]]) size = arr.size print(size)
Counting occurrences of a character in a string or an array
The np.char.count() function can be used to count the total number of occurrences of a character in a string or an array. It returns the number of occurrences of the specified character in the input array. Here’s an example code snippet:
import numpy as nparr = np.array(['apple', 'banana', 'cherry']) count = np.char.count(arr, 'a') print(count)
Using len() function to count the number of elements in an array
The len() function can be used to find the total number of elements in an array. It returns the length of the input array. Here’s an example code snippet:
import numpy as nparr = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 1]]) length = len(arr) print(length)
Counting non-masked elements of an array along a given axis
The numpy.ma.count() function can be used to count the non-masked elements of an array along a given axis. It returns the number of non-masked elements in the input array along the specified axis. Here’s an example code snippet:
import numpy as nparr = np.ma.array([[0, 1, 0], [1, 1, 1], [0, 0, 1]], mask=[[True, False, False], [False, False, False], [True, True, False]]) count = np.ma.count(arr, axis=0) print(count)
Counting the number of occurrences of each value in an array
The numpy.bincount() function can be used to count the number of occurrences of each value in an array of non-negative integers. It returns an array of length max(input_array) + 1 , where the i-th element is the number of occurrences of the i-th value in the input array. Here’s an example code snippet:
import numpy as nparr = np.array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0]) counts = np.bincount(arr) print(counts)
Counting non-masked elements of an array along a given axis
The numpy.ma.MaskedArray.count() function can be used to count the non-masked elements of an array along a given axis. It returns the number of non-masked elements in the input array along the specified axis. Here’s an example code snippet:
import numpy as nparr = np.ma.array([[0, 1, 0], [1, 1, 1], [0, 0, 1]], mask=[[True, False, False], [False, False, False], [True, True, False]]) count = np.ma.MaskedArray.count(arr, axis=0) print(count)
Other simple code examples for counting elements in a NumPy array with Python
In Python , np array value count code sample
unique_elements, counts_elements = np.unique(a, return_counts=True)
In Python as proof, number of elements in the array numpy code example
import numpy as np arr = np.array([1,2,3]) arr.size
Conclusion
In conclusion, Python provides various methods to count the number of elements in a NumPy array. The methods discussed in this blog post include Counting True elements in a NumPy array, counting occurrences of values in a NumPy array, finding the total number of elements in an array, counting occurrences of a character in a string or an array, using the len() function to count the number of elements in an array, counting non-masked elements of an array along a given axis, and counting the number of occurrences of each value in an array. Using appropriate functions in NumPy can simplify complex operations in Python.