code: def _auto_pivot(
      df: pd.DataFrame,
      column_prefixes: _ColumnPrefixes,
      stringify_slices: bool,
      collapse_column_names: bool,
  ) -> pd.DataFrame:
      """Implements auto_pivot."""
      df = (
          _stringify_slices(df, column_prefixes.slices)
          if stringify_slices
          else df
      )
      # TODO(b/277280388): Use Series.sort_values after upgrading to pandas > 1.2.
      # See https://github.com/pandas-dev/pandas/issues/35922
      # Replace the df_unique logic with the following block.
      # df_unique = (
      #     df[column_prefixes.metric_keys]
      #     .nunique(dropna=False)
      #     .sort_index()
      #     .sort_values(ascending=False, kind='stable')
      # )
      df_unique = (
          df[column_prefixes.metric_keys]
          .nunique(dropna=False)
          .sort_index()
      )
      _, tags = np.unique(df_unique.values, return_inverse=True)
      df_unique = df_unique.iloc[np.argsort(-tags, kind="stable")]
  
      pivot_columns = [
          (column_prefixes.metric_keys, column)
          for column, nunique in df_unique.items()
          if nunique > 1
      ]
      metric_value_columns = df[column_prefixes.metric_values].columns
      slice_columns = df[column_prefixes.slices].columns
      value_columns = [
          (column_prefixes.metric_values, c)
          for c in metric_value_columns
      ]
      index_columns = [
          (column_prefixes.slices, c) for c in slice_columns
      ]
      result = df.pivot(
          index=index_columns,
          columns=pivot_columns,
          values=value_columns,
      )
      if stringify_slices:
          result.index.name = column_prefixes.slices
      if collapse_column_names and isinstance(
          result.columns, pd.MultiIndex
      ):
          result.columns = _collapse_column_names(result.columns)
      return result
  
imports: import collections
  import dataclasses
  import itertools
  from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union
  import numpy
  import pandas
  from tensorflow_model_analysis.proto import metrics_for_slice_pb2
  from google.protobuf import wrappers_pb2
  from google.protobuf import descriptor
  from google.protobuf import message
label_desc: Use image node_id 8 for calling a global function with example usage: _auto_pivot(df, column_prefixes, stringify_slices, collapse_column_names) and returns: result