Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use python to find the most frequent values

Shulou Source: shulou.com Published: 2022-06-01 05:16:21 09月29日 Update

This article will explain in detail how to use python to find the most frequent values. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Find the values that appear most frequently

To find the values that appear most frequently in a list or string:

Test = [1,2,3,4,2,2,3,1,4,4] print (max (set (test), key = test.count)) # 4

Max () returns the maximum value in the list. The key parameter takes a single parameter function to customize the sort order, in this case test.count, which applies to each item on the iterator.

Test.count is a built-in feature of list. It takes a parameter and calculates the number of occurrences of that parameter. So test.count (1) will return 2 and test.count (4) will return 4.

Set (test) returns all unique values in test, so {1, 2, 3, 4}

Then this line of code will accept all the unique values of test, that is, {1, 2, 3, 4}. Next, max will apply the list.count function to it and return the maximum value.

There is a more effective way:

From collections import Counter Counter (test). Most_common (1) # [4: 4] this is the end of the article on "how to use python to find the most frequent values". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Frequent parameter function article maximum more maximum good practical effective next line code content function single character string will be right article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info OPPO Reno Redmi Huawei