code: def _group(
      metrics_df: pd.DataFrame,
      plotters: Collection[Plotter],
      metadata: Collection[BenchmarkMetadata],
      by: Sequence[GroupingKey],
  ) -> Sequence[
      Tuple[Tuple[str, ...], pd.DataFrame, Collection[Plotter]]
  ]:
      """
      Group the given data by the given columns.
      """
      if not by:
          return [((), metrics_df, plotters)]
  
      joined_df = metrics_df
  
      metadata_by_columns = [
          k.key_name
          for k in by
          if k.key_source == GroupingKeySource.METADATA
      ]
      if metadata_by_columns:
          metadata_columns = ["run_id"] + metadata_by_columns
          metadata_df = pd.DataFrame(
              [
                  [getattr(md, c) for c in metadata_columns]
                  for md in metadata
              ],
              columns=metadata_columns,
          )
          joined_df = pd.merge(joined_df, metadata_df, on="run_id")
  
      plotter_by_columns = [
          k.key_name
          for k in by
          if k.key_source == GroupingKeySource.PLOTTER
      ]
      if plotter_by_columns:
          plotter_key_name = GroupingKey.PLOTTER.key_name
          assert plotter_by_columns == [plotter_key_name]
          plotter_df = pd.DataFrame(
              {plotter_key_name: [p.name for p in plotters]}
          )
          joined_df = joined_df.merge(plotter_df, how="cross")
  
      result = []
      for keys, df in joined_df.groupby([k.key_name for k in by]):
          keys, key_plotters = _sanitise_keys(by, keys, plotters)
          if metadata_by_columns:
              df = df.drop(columns=metadata_by_columns)
          if plotter_by_columns:
              df = df.drop(columns=plotter_by_columns)
          result.append((keys, df, key_plotters))
      return result
  
imports: import heapq
  from dataclasses import dataclass
  from enum import Enum
  from typing import Any, Collection, Iterator, List, Sequence, Tuple, Type
  import pandas
  from benchmark.metadata import BenchmarkMetadata
  from benchmark.plotter_api import Plotter
label_desc: Use image node_id 2 for calling a global function with example usage: _group(metrics_df, plotters, metadata, by) and returns: result, list