Search results
Apr 8, 2010 · Counting all items with count() To count the occurrences of items in l one can simply use a list comprehension and the count() method [[x,l.count(x)] for x in set(l)] (or similarly with a dictionary dict((x,l.count(x)) for x in set(l))) Example:
Nov 11, 2009 · Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation. Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
Dec 24, 2016 · If you are interested in the fastest execution, you know in advance which value(s) to look for, and your array is 1D, or you are otherwise interested in the result on the flattened array (in which case the input of the function should be np.ravel(arr) rather than just arr), then Numba is your friend:
Jun 29, 2017 · "Well, to count the number of elements of a list, there is no way round checking all the elements." I could make an list implementation where count is O(1) by keeping track of the occurrences and increment when the same value is appended. Just didn't want to make any assumption about Python's implementation. –
For finding instances of a specific substring, I would use a regular expression or the str.count() method. I haven't tested, but there may be a performance difference due to a slight overhead in counting all characters and appending to a dictionary rather than counting occurrences of a single substring.
Apr 23, 2014 · I am trying to find a simple way of getting a count of the number of elements repeated in a list e.g ...
You can use the in-built function provided in python. l.count(l[i]) d=[] for i in range(len(l)): if l[i] not in d: d.append(l[i]) print(l.count(l[i]) The above code automatically removes duplicates in a list and also prints the frequency of each element in original list and the list without duplicates.
Feb 12, 2014 · For kicks, I wrote up an answer using a decorator: class counter: #wraps a function, to keep a running count of how many #times it's been called def __init__(self, func): self.func = func self.count = count def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs)
The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).
Apr 3, 2019 · Find the count of non-NA value across the row axis. df.count(axis = 0) Output: A 5 B 4 C 5 dtype: int64 Find the number of non-NA/null value across the column. df.count(axis = 1) Output: 0 3 1 2 2 3 3 1 4 2 5 3 dtype: int64 value_counts() function returns Series containing counts of unique values.