Pandas DataFrame: stack() function
DataFrame - stack() function
The stack() function is used to 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.
Syntax:
DataFrame.stack(self, level=-1, dropna=True)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
level | Level(s) to stack from the column axis onto the index axis, defined as one index or label, or a list of indices or labels. | int, str, list Default Value: 1 |
Required |
dropna | Whether to drop rows in the resulting Frame/Series with missing values. Stacking a column level onto the index axis can create combinations of index and column values that are missing from the original dataframe. | bool Default Value: True |
Required |
Returns: DataFrame or Series
Stacked dataframe or series.
Example:
Download the Pandas DataFrame Notebooks from here.
Previous: DataFrame - nsmallest() function
Next: DataFrame - unstack() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/dataframe/dataframe-stack.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics