Home > Mobile >  Getting highest value out of a dataframe with value_counts()
Getting highest value out of a dataframe with value_counts()

Time:10-02

I want to print out the highest, not unique value out of my dataframe. With df['Value'].value_counts() i can count them, but how do i selected them by how often the numbers appear.

Value
1
2
1
2
3
2

CodePudding user response:

As I understand you want the first highest value that has a frequency greater than 1. In this case you can write,

for val, cnt in df['Value'].value_counts().sort_index(ascending=False).iteritems():
  if cnt > 1:
    print(val)
    break

The sort_index sorts the items by the 'Value' rather than the frequencies. For example if your 'Value' columns has values [1, 2, 3, 3, 2, 2,2, 1, 3, 2] then the result of df['Value'].value_counts().sort_index(ascending=False).iteritems() will be as follows,

3    3
2    5
1    2
Name: Value, dtype: int64

The answer in this example would then be 3 since it is the first highest value with frequency greater than 1.

  • Related