How to stack Pandas DataFrame

In this article, you will learn how to stack Pandas DataFrame. A Pandas DataFrame is nothing but a two-dimensional data structure or two-dimensional array that…


This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan

In this article, you will learn how to stack Pandas DataFrame.

A Pandas DataFrame is nothing but a two-dimensional data structure or two-dimensional array that represents the data in rows and columns. In other words, it is compared to rectangular grids used to store data. It is open-source and potent, fast, and easy to use. Basically, while working with big data we need to analyze, manipulate and update them and the pandas’ library plays a lead role there.

Sometimes, We need to reshape the Pandas DataFrame into a table. The easiest way to perform this action is to use the stack() method. We can stack a Pandas DataFrame in a single level or multi-level. This method accepts two parameters first one is level which is required and the second one is dropna with a value of True and False. This parameter is optional. In this article, we will explore this method and see how we can stack Pandas DataFrame. First, let’s create a simple Pandas DataFrame in the below section:

import pandas as pd

student_df = pd.DataFrame([['Alex', 19], ['Deven', 21]],
                           ['Alex_Details', 'Deven_details'],
                            columns=['Name', 'Age'])


print(student_df)

# Output:
#                 Name  Age
# Alex_Details    Alex   19
# Deven_details  Deven   21

Here, we have created a simple Pandas DataFrame that represents two students’ details. This DataFrame consists of single-level columns with the details of Name and Marks. We will reshape this DataFrame by using the stack() method in the next section.

Example One: stack Pandas DataFrame in single-level

We can stack Pandas DataFrame in single level column. This is the easiest way to perform this action. All we need to do is to mention the DataFrame name and then access the stack() method. Follow the below code example:

import pandas as pd

student_df = pd.DataFrame([['Alex', 19], ['Deven', 21]],
                           ['Alex_Details', 'Deven_details'],
                            columns=['Name', 'Age'])

single_stack_df = student_df.stack()
print(single_stack_df)

# Output:
# Alex_Details   Name     Alex
#                Age        19
# Deven_details  Name    Deven
#                Age        21
# dtype: object

Here, you can see that we use the stack method to reshape the DataFrame. We store the result into a new variable. Finally, you can see the changes in the output.

Example Two: stack Pandas DataFrame in multi-level

In the previous example, we have seen how we can reshape the DataFrame that consists of single level column. What if we need to reshape a multi-level columns DataFrame? How can we perform this action? To do so, follow the below code example:

import pandas as pd

multi_column = pd.MultiIndex.from_tuples([('student_details', 'Name'),
                                       ('student_details', 'Age')])
student_df = pd.DataFrame([['Alex', 19], ['Deven', 21]],
                           ['Alex_Details', 'Deven_details'],
                            columns=multi_column)

multi_stack_df = student_df.stack()
print(multi_stack_df)

# Output:
#                    student_details
# Alex_Details  Age               19
#               Name            Alex
# Deven_details Age               21
#               Name           Deven

Here, you can see that our DataFrame has a common column name and each column consists of two more columns. We simply, reshape this DataFrame by using the stack() method. If you need to perform this action in your program, you can simply follow these approaches.


This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan


Print Share Comment Cite Upload Translate Updates
APA

Md Niaz Rahman Khan | Sciencx (2022-10-01T16:27:00+00:00) How to stack Pandas DataFrame. Retrieved from https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/

MLA
" » How to stack Pandas DataFrame." Md Niaz Rahman Khan | Sciencx - Saturday October 1, 2022, https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/
HARVARD
Md Niaz Rahman Khan | Sciencx Saturday October 1, 2022 » How to stack Pandas DataFrame., viewed ,<https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/>
VANCOUVER
Md Niaz Rahman Khan | Sciencx - » How to stack Pandas DataFrame. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/
CHICAGO
" » How to stack Pandas DataFrame." Md Niaz Rahman Khan | Sciencx - Accessed . https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/
IEEE
" » How to stack Pandas DataFrame." Md Niaz Rahman Khan | Sciencx [Online]. Available: https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/. [Accessed: ]
rf:citation
» How to stack Pandas DataFrame | Md Niaz Rahman Khan | Sciencx | https://www.scien.cx/2022/10/01/how-to-stack-pandas-dataframe/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.