2

I have a pandas dataframe that looks like this:

Hr  Loc Freq    
0   79  5546

0   132 5456

0   48  4359

0   249 4089

0   230 3485
... ... ...
23  227 1
23  240 1
23  250 1
23  251 1
23  258 1 

It contains about 5000 rows with the "Hr" column as index. I want to group the dataframe by Hr and find the "Loc" that has the highest (Freq)Frequency value.

I have done this:

location.groupby(['Hour']).Frequency.max()

which created a new Series:

Hr
0      5546
1      5394
2      3745
3      2500
4      1232
5      2387
6      5690
7      6164
8      7354
9      8346
10     8846
11     9974
12    10718
13    11031
14    12306
15    12159
16    11482
17    11876
18    12079
19    11332
20    10285
21    10611
22    11031
23    10181

that has the highest Frequency values, but it doesn't have the corresponding "Loc" value that matches it. How do I create or include that?

What I want is something like this:

Hr Loc Freq
0  79  5546
... ... ...
23 59  10181
azaya
  • 21
  • 3
  • [Please don't post pictures of text](https://meta.stackoverflow.com/q/285551/4518341), post the text itself and use the formatting tools like [code formatting](/editing-help#code). Also, please provide a [mre], meaning complete example data and desired output. For specifics, see [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Apr 02 '23 at 21:47
  • BTW, welcome back to Stack Overflow! Check out the [tour], and [ask] if you want tips, like how to write a good title. – wjandrea Apr 02 '23 at 21:48
  • 1
    Duplicate: [Get the row(s) which have the max value in groups using groupby](/q/15705630/4518341) – wjandrea Apr 02 '23 at 22:04
  • (Sorry, I would have posted that first, but I forgot it existed.) – wjandrea Apr 02 '23 at 22:05

1 Answers1

1

You can try leverage idxmax:

Return index of first occurrence of maximum over requested axis.

result = df.loc[df.groupby(['Hr']).Freq.idxmax()]

Note that as quote says - in case of duplicate maximums the first row will be returned.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132