Preparation
Before any data manipulation can occur, two (2) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The Xarray library works with labeled multi-dimensional arrays and advanced analytics.
To install these libraries, navigate to an IDE terminal. At the command prompt ($
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($
). Your terminal prompt may be different.
$ pip install pandas
Hit the <Enter>
key on the keyboard to start the installation process.
$ pip install xarray
Hit the <Enter>
key on the keyboard to start the installation process.
If the installations were successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required library.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import xarray
DataFrame explode()
The explode()
method reshapes (transforms) the DataFrame/Series elements from a list-like scenario to a row format.
The syntax for this method is as follows:
DataFrame.explode(column, ignore_index=False)
column | This parameter is the column(s) to explode (string, tuple, or list format). |
ignore_index | If True , the index labels will be 0, 1, 2, etc. If False , the set index displays. |
For this example, a public school conducts three (3) classes per day for three (3) grades (6-8).
Each grade contains a list with the number of students per class. For example, the Grade-7 class explodes to display each element inside the list in a long (vertical) format.
df = pd.DataFrame({'Grade-6': [[15, 11, 10]], 'Grade-7': [[12, 16, 11]], 'Grade-8': [[20, 18, 19]]}) print(df) result = df.explode('Grade-7') print(result)
- Line [1] creates a DataFrame from a Dictionary containing class details and saves it to
df
. - Line [2] outputs the DataFrame to the terminal.
- Line [3] explodes the format for Grade-7. This output saves to
result
. - Line [4] outputs the result to the terminal.
Output
df
Grade-6 | Grade-7 | Grade-8 | |
0 | [15, 11, 10] | [12, 16, 11] | [20, 18, 19] |
result
Grade-6 | Grade-7 | Grade-8 | |
0 | [15, 11, 10] | 12 | [20, 18, 19] |
0 | [15, 11, 10] | 16 | [20, 18, 19] |
0 | [15, 11, 10] | 11 | [20, 18, 19] |
More Pandas DataFrame Methods
Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:
Also, check out the full cheat sheet overview of all Pandas DataFrame methods.