title: How can I select and index the highest value in each group of a Pandas dataframe?
body: <p>I have a dataframe with multiple columns, each combination of columns describing one experiment (e.g. multiple super-labels, for each super-label multiple episodes with different number of timesteps). I want to set the last timestep in each episode for all experiments to True, but I can't figure out how to do this. I have tried three different approaches, all using <code>.loc</code> and 1) using <code>.max().index</code>, 2) <code>.idxmax()</code> and 3) <code>.tail(1).index</code>, but they all fail (the first two with for me ununderstandable exceptions and the last one being wrong.</p>
  <p>This is my minimal example:</p>
  <pre><code>import numpy as np
  import pandas as pd
  
  np.random.seed(4)
  def gen(t):
      results = []
      for episode_id, episode in enumerate(range(np.random.randint(2, 4))):
          for i in range(np.random.randint(2, 6)):
              results.append(
                  {
                      &quot;episode&quot;: episode_id,
                      &quot;timestep&quot;: i,
                      &quot;t&quot;: t,
                  }
              )
      return pd.DataFrame(results)
  
  df = pd.concat([gen(&quot;a&quot;), gen(&quot;b&quot;)])
  
  base_groups = [&quot;t&quot;, &quot;episode&quot;]
  
  df[&quot;last_timestep&quot;] = False
  
  print(&quot;Expected:&quot;)
  print(df.groupby(base_groups).timestep.max())
  
  #df.loc[df.groupby(base_groups).timestep.max().index, &quot;last_timestep&quot;] = True
  #df.loc[df.groupby(base_groups).timestep.idxmax(), &quot;last_timestep&quot;] = True
  df.loc[df.groupby(base_groups).tail(1).index, &quot;last_timestep&quot;] = True
  
  print(&quot;Is:&quot;)
  print(df[df.last_timestep])
  </code></pre>
  <p>The output of <code>df.groupby(base_groups).timestep.max()</code> is exactly what I expect, the correct rows are selected:</p>
  <pre><code>Expected:
  t  episode
  a  0          3
     1          4
  b  0          2
     1          1
     2          4
  </code></pre>
  <p>But when filtering the dataframe, this is what I get:</p>
  <pre><code>Is:
     episode  timestep  t  last_timestep
  2        0         2  a           True
  3        0         3  a           True
  4        1         0  a           True
  8        1         4  a           True
  2        0         2  b           True
  3        1         0  b           True
  4        1         1  b           True
  8        2         3  b           True
  9        2         4  b           True
  </code></pre>
  <p>The rows 0, 2, 5 and 7 should not be selected.</p>