def stack(self) -> DataFrameOrSeries:
    "\n        Stack the prescribed level(s) from columns to index.\n\n        Return a reshaped DataFrame or Series having a multi-level\n        index with one or more new inner-most levels compared to the current\n        DataFrame. The new inner-most levels are created by pivoting the\n        columns of the current dataframe:\n\n          - if the columns have a single level, the output is a Series;\n          - if the columns have multiple levels, the new index\n            level(s) is (are) taken from the prescribed level(s) and\n            the output is a DataFrame.\n\n        The new index levels are sorted.\n\n        Returns\n        -------\n        DataFrame or Series\n            Stacked dataframe or series.\n\n        See Also\n        --------\n        DataFrame.unstack : Unstack prescribed level(s) from index axis\n            onto column axis.\n        DataFrame.pivot : Reshape dataframe from long format to wide\n            format.\n        DataFrame.pivot_table : Create a spreadsheet-style pivot table\n            as a DataFrame.\n\n        Notes\n        -----\n        The function is named by analogy with a collection of books\n        being reorganized from being side by side on a horizontal\n        position (the columns of the dataframe) to being stacked\n        vertically on top of each other (in the index of the\n        dataframe).\n\n        Examples\n        --------\n        **Single level columns**\n\n        >>> df_single_level_cols = ps.DataFrame([[0, 1], [2, 3]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=['weight', 'height'])\n\n        Stacking a dataframe with a single level column axis returns a Series:\n\n        >>> df_single_level_cols\n             weight  height\n        cat       0       1\n        dog       2       3\n        >>> df_single_level_cols.stack().sort_index()\n        cat  height    1\n             weight    0\n        dog  height    3\n             weight    2\n        dtype: int64\n\n        **Multi level columns: simple case**\n\n        >>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n        ...                                        ('weight', 'pounds')])\n        >>> df_multi_level_cols1 = ps.DataFrame([[1, 2], [2, 4]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=multicol1)\n\n        Stacking a dataframe with a multi-level column axis:\n\n        >>> df_multi_level_cols1  # doctest: +NORMALIZE_WHITESPACE\n            weight\n                kg pounds\n        cat      1      2\n        dog      2      4\n        >>> df_multi_level_cols1.stack().sort_index()\n                    weight\n        cat kg           1\n            pounds       2\n        dog kg           2\n            pounds       4\n\n        **Missing values**\n\n        >>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n        ...                                        ('height', 'm')])\n        >>> df_multi_level_cols2 = ps.DataFrame([[1.0, 2.0], [3.0, 4.0]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=multicol2)\n\n        It is common to have missing values when stacking a dataframe\n        with multi-level columns, as the stacked dataframe typically\n        has more values than the original dataframe. Missing values\n        are filled with NaNs:\n\n        >>> df_multi_level_cols2\n            weight height\n                kg      m\n        cat    1.0    2.0\n        dog    3.0    4.0\n        >>> df_multi_level_cols2.stack().sort_index()  # doctest: +SKIP\n                height  weight\n        cat kg     NaN     1.0\n            m      2.0     NaN\n        dog kg     NaN     3.0\n            m      4.0     NaN\n        "
    from pyspark.pandas.series import first_series
    if (len(self._internal.column_labels) == 0):
        return DataFrame(self._internal.copy(column_label_names=self._internal.column_label_names[:(- 1)]).with_filter(SF.lit(False)))
    column_labels: Dict[(Label, Dict[(Any, Column)])] = defaultdict(dict)
    index_values = set()
    should_returns_series = False
    for label in self._internal.column_labels:
        new_label = label[:(- 1)]
        if (len(new_label) == 0):
            new_label = None
            should_returns_series = True
        value = label[(- 1)]
        scol = self._internal.spark_column_for(label)
        column_labels[new_label][value] = scol
        index_values.add(value)
    column_labels = dict(sorted(column_labels.items(), key=(lambda x: x[0])))
    index_name = self._internal.column_label_names[(- 1)]
    column_label_names = self._internal.column_label_names[:(- 1)]
    if (len(column_label_names) == 0):
        column_label_names = [None]
    index_column = SPARK_INDEX_NAME_FORMAT(self._internal.index_level)
    data_columns = [name_like_string(label) for label in column_labels]
    structs = [F.struct(*[SF.lit(value).alias(index_column)], *[(column_labels[label][value] if (value in column_labels[label]) else SF.lit(None)).alias(name) for (label, name) in zip(column_labels, data_columns)]).alias(value) for value in index_values]
    pairs = F.explode(F.array(*structs))
    sdf = self._internal.spark_frame.withColumn('pairs', pairs)
    sdf = sdf.select(((self._internal.index_spark_columns + [sdf['pairs'][index_column].alias(index_column)]) + [sdf['pairs'][name].alias(name) for name in data_columns]))
    internal = InternalFrame(spark_frame=sdf, index_spark_columns=[scol_for(sdf, col) for col in (self._internal.index_spark_column_names + [index_column])], index_names=(self._internal.index_names + [index_name]), index_fields=(self._internal.index_fields + [None]), column_labels=list(column_labels), data_spark_columns=[scol_for(sdf, col) for col in data_columns], column_label_names=column_label_names)
    psdf: DataFrame = DataFrame(internal)
    if should_returns_series:
        return first_series(psdf)
    else:
        return psdf
Stack the prescribed level(s) from columns to index.

Return a reshaped DataFrame or Series having a multi-level
index with one or more new inner-most levels compared to the current
DataFrame. The new inner-most levels are created by pivoting the
columns of the current dataframe:

  - if the columns have a single level, the output is a Series;
  - if the columns have multiple levels, the new index
    level(s) is (are) taken from the prescribed level(s) and
    the output is a DataFrame.

The new index levels are sorted.

Returns
-------
DataFrame or Series
    Stacked dataframe or series.

See Also
--------
DataFrame.unstack : Unstack prescribed level(s) from index axis
    onto column axis.
DataFrame.pivot : Reshape dataframe from long format to wide
    format.
DataFrame.pivot_table : Create a spreadsheet-style pivot table
    as a DataFrame.

Notes
-----
The function is named by analogy with a collection of books
being reorganized from being side by side on a horizontal
position (the columns of the dataframe) to being stacked
vertically on top of each other (in the index of the
dataframe).

Examples
--------
**Single level columns**

>>> df_single_level_cols = ps.DataFrame([[0, 1], [2, 3]],
...                                     index=['cat', 'dog'],
...                                     columns=['weight', 'height'])

Stacking a dataframe with a single level column axis returns a Series:

>>> df_single_level_cols
     weight  height
cat       0       1
dog       2       3
>>> df_single_level_cols.stack().sort_index()
cat  height    1
     weight    0
dog  height    3
     weight    2
dtype: int64

**Multi level columns: simple case**

>>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),
...                                        ('weight', 'pounds')])
>>> df_multi_level_cols1 = ps.DataFrame([[1, 2], [2, 4]],
...                                     index=['cat', 'dog'],
...                                     columns=multicol1)

Stacking a dataframe with a multi-level column axis:

>>> df_multi_level_cols1  # doctest: +NORMALIZE_WHITESPACE
    weight
        kg pounds
cat      1      2
dog      2      4
>>> df_multi_level_cols1.stack().sort_index()
            weight
cat kg           1
    pounds       2
dog kg           2
    pounds       4

**Missing values**

>>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),
...                                        ('height', 'm')])
>>> df_multi_level_cols2 = ps.DataFrame([[1.0, 2.0], [3.0, 4.0]],
...                                     index=['cat', 'dog'],
...                                     columns=multicol2)

It is common to have missing values when stacking a dataframe
with multi-level columns, as the stacked dataframe typically
has more values than the original dataframe. Missing values
are filled with NaNs:

>>> df_multi_level_cols2
    weight height
        kg      m
cat    1.0    2.0
dog    3.0    4.0
>>> df_multi_level_cols2.stack().sort_index()  # doctest: +SKIP
        height  weight
cat kg     NaN     1.0
    m      2.0     NaN
dog kg     NaN     3.0
    m      4.0     NaN
def stack(self) -> DataFrameOrSeries:
    "\n        Stack the prescribed level(s) from columns to index.\n\n        Return a reshaped DataFrame or Series having a multi-level\n        index with one or more new inner-most levels compared to the current\n        DataFrame. The new inner-most levels are created by pivoting the\n        columns of the current dataframe:\n\n          - if the columns have a single level, the output is a Series;\n          - if the columns have multiple levels, the new index\n            level(s) is (are) taken from the prescribed level(s) and\n            the output is a DataFrame.\n\n        The new index levels are sorted.\n\n        Returns\n        -------\n        DataFrame or Series\n            Stacked dataframe or series.\n\n        See Also\n        --------\n        DataFrame.unstack : Unstack prescribed level(s) from index axis\n            onto column axis.\n        DataFrame.pivot : Reshape dataframe from long format to wide\n            format.\n        DataFrame.pivot_table : Create a spreadsheet-style pivot table\n            as a DataFrame.\n\n        Notes\n        -----\n        The function is named by analogy with a collection of books\n        being reorganized from being side by side on a horizontal\n        position (the columns of the dataframe) to being stacked\n        vertically on top of each other (in the index of the\n        dataframe).\n\n        Examples\n        --------\n        **Single level columns**\n\n        >>> df_single_level_cols = ps.DataFrame([[0, 1], [2, 3]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=['weight', 'height'])\n\n        Stacking a dataframe with a single level column axis returns a Series:\n\n        >>> df_single_level_cols\n             weight  height\n        cat       0       1\n        dog       2       3\n        >>> df_single_level_cols.stack().sort_index()\n        cat  height    1\n             weight    0\n        dog  height    3\n             weight    2\n        dtype: int64\n\n        **Multi level columns: simple case**\n\n        >>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n        ...                                        ('weight', 'pounds')])\n        >>> df_multi_level_cols1 = ps.DataFrame([[1, 2], [2, 4]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=multicol1)\n\n        Stacking a dataframe with a multi-level column axis:\n\n        >>> df_multi_level_cols1  # doctest: +NORMALIZE_WHITESPACE\n            weight\n                kg pounds\n        cat      1      2\n        dog      2      4\n        >>> df_multi_level_cols1.stack().sort_index()\n                    weight\n        cat kg           1\n            pounds       2\n        dog kg           2\n            pounds       4\n\n        **Missing values**\n\n        >>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n        ...                                        ('height', 'm')])\n        >>> df_multi_level_cols2 = ps.DataFrame([[1.0, 2.0], [3.0, 4.0]],\n        ...                                     index=['cat', 'dog'],\n        ...                                     columns=multicol2)\n\n        It is common to have missing values when stacking a dataframe\n        with multi-level columns, as the stacked dataframe typically\n        has more values than the original dataframe. Missing values\n        are filled with NaNs:\n\n        >>> df_multi_level_cols2\n            weight height\n                kg      m\n        cat    1.0    2.0\n        dog    3.0    4.0\n        >>> df_multi_level_cols2.stack().sort_index()  # doctest: +SKIP\n                height  weight\n        cat kg     NaN     1.0\n            m      2.0     NaN\n        dog kg     NaN     3.0\n            m      4.0     NaN\n        "
    from pyspark.pandas.series import first_series
    if (len(self._internal.column_labels) == 0):
        return DataFrame(self._internal.copy(column_label_names=self._internal.column_label_names[:(- 1)]).with_filter(SF.lit(False)))
    column_labels: Dict[(Label, Dict[(Any, Column)])] = defaultdict(dict)
    index_values = set()
    should_returns_series = False
    for label in self._internal.column_labels:
        new_label = label[:(- 1)]
        if (len(new_label) == 0):
            new_label = None
            should_returns_series = True
        value = label[(- 1)]
        scol = self._internal.spark_column_for(label)
        column_labels[new_label][value] = scol
        index_values.add(value)
    column_labels = dict(sorted(column_labels.items(), key=(lambda x: x[0])))
    index_name = self._internal.column_label_names[(- 1)]
    column_label_names = self._internal.column_label_names[:(- 1)]
    if (len(column_label_names) == 0):
        column_label_names = [None]
    index_column = SPARK_INDEX_NAME_FORMAT(self._internal.index_level)
    data_columns = [name_like_string(label) for label in column_labels]
    structs = [F.struct(*[SF.lit(value).alias(index_column)], *[(column_labels[label][value] if (value in column_labels[label]) else SF.lit(None)).alias(name) for (label, name) in zip(column_labels, data_columns)]).alias(value) for value in index_values]
    pairs = F.explode(F.array(*structs))
    sdf = self._internal.spark_frame.withColumn('pairs', pairs)
    sdf = sdf.select(((self._internal.index_spark_columns + [sdf['pairs'][index_column].alias(index_column)]) + [sdf['pairs'][name].alias(name) for name in data_columns]))
    internal = InternalFrame(spark_frame=sdf, index_spark_columns=[scol_for(sdf, col) for col in (self._internal.index_spark_column_names + [index_column])], index_names=(self._internal.index_names + [index_name]), index_fields=(self._internal.index_fields + [None]), column_labels=list(column_labels), data_spark_columns=[scol_for(sdf, col) for col in data_columns], column_label_names=column_label_names)
    psdf: DataFrame = DataFrame(internal)
    if should_returns_series:
        return first_series(psdf)
    else:
        return psdf