# Python Numpy count elements

As you already know, in order to calculate non-zero elements in your np array, you can use numpy.count_nonzero. But how about 0? How about an expression? Well, as it turns out, you can calculate 0s with count_nonzero() as well. Seems counter intuitive? Maybe not. Let’ see an example:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 import numpy as np x = np.arange(20).reshape(4,5) y = x % 3 == 0 y = y.astype(int) # optional, if dealing with only 1s and 0s # simple np.count_nonzero(y == 1) # 7 np.count_nonzero(y == 0) # 13 (y == 1).sum() # 7 (y == 0).sum() # 13 # slightly complex np.count_nonzero(x > 5) # 14 (x > 9).sum() # 10

Another example …

So let’s say you were doing some statistical image computation on a binary (0-1) image (whose pixels are either 0 or 1, i.e. black or white) and you needed to compute a black pixel ratio, in other words, ratio of black pixels to total pixels. In addition to what we discussed above, there seems also another way to do this.

The second approach below is particularly handy, if you are interested in calculating the total number of white and black pixel counts in your binary image. The caveat in the second approach is, whilst, working with complete white or complete black image, your dictionary (here, the variable d) would not have a key for 0 and 1 respectively. Lines 25 and 28 should take care of that. But if this does not apply for you, then certainly you can ignore this consideration

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 >>> image array([[1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 0, 0], [1, 0, 0, 1, 0]]) >>> black_pixel_count = (image == 0).sum() >>> total_pixel_count 20 >>> total_pixel_count = image.shape * image.shape >>> total_pixel_count 20 >>> black_pixel_ratio = black_pixel_count / float(total_pixel_count) >>> black_pixel_ratio 0.65000000000000002 >>> import collections >>> k, v = np.unique(y, return_counts=True) >>> k array([0, 1]) >>> v array([13, 7]) >>> d = dict(zip(k,v)) >>> if 0 not in d: ... d = 0 ... >>> if 1 not in d: ... d = 0 ... >>> >>> d {0: 13, 1: 7} >>> d 13 >>> d 7
{"ft_lang_label":"__label__en","ft_lang_prob":0.78238356,"math_prob":0.8631309,"size":2037,"snap":"2022-40-2023-06","text_gpt3_token_len":660,"char_repetition_ratio":0.12985735,"word_repetition_ratio":0.0,"special_character_ratio":0.38684338,"punctuation_ratio":0.19861431,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98622966,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-10-01T01:40:07Z\",\"WARC-Record-ID\":\"<urn:uuid:d47f1255-df62-4ba0-a942-baefc385ad35>\",\"Content-Length\":\"131442\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e3018f1e-8088-4cb2-97d2-369f02d2196b>\",\"WARC-Concurrent-To\":\"<urn:uuid:2eb95db7-1fba-4bba-a818-5b0e8519420c>\",\"WARC-IP-Address\":\"192.0.78.24\",\"WARC-Target-URI\":\"https://aarsh.dev/2017/10/15/python-numpy-count-elements/\",\"WARC-Payload-Digest\":\"sha1:NPGWIOUOLXU7WA5JAD2WD57YDMGJIO6S\",\"WARC-Block-Digest\":\"sha1:XEGEJZGN4PMURVTPHR4FB7BSXBYZBBL3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030335514.65_warc_CC-MAIN-20221001003954-20221001033954-00768.warc.gz\"}"}