Python is a high-level programming language that makes the analysis of data easier. While working on the big dataset as well as on the small one, developers may need to clean, update, or transform it. They can modify the way the data is presented. Data modification can be gained using multiple Python functions.
This post will talk about:
What is the “explode()” Function in Python?
The explode()” function is used for modifying or transforming each member of an array or element of list into a row. It converts the element of the list to a row while replacing the index values returning the DataFrame exploded element lists.
Syntax
The general syntax of the “explode()” function is provided below:
The above-mentioned function takes two parameters, the first parameter “column” represents the specific element of a column that is to explode and is the required parameter. On the other hand, the “ignore_index” is an optional keyword argument parameter.
How to Explode Multiple Columns Using the “explode()” Function in Python?
To explode the multiple columns using the “explode()” function in Python, check out the provided example.
Example
First, import the “pandas” and “numpy” modules. Then, create a new DataFrame as “courses” and provide values. After that, display the newly created DataFrame values:
import numpy as np
courses = ({'A' : [["Maria", "Henry", "Marry"], 'Alex', ["David", "Peter"]],
'B' : [["Algorithm", "Big Data", "Networking" ], 'Data Mining',
[ "Machine Learning", "Research Methodology"]],
'C' : ['010', '023', '016']
})
df = pd.DataFrame(courses)
print(df)
As you can see, the newly created DataFrame has been displayed below:
Now, explode the multiple columns of DataFrame, call the “list()” function with DataFrame columns labeled as an argument inside the “explode()” function, and pass it to the “df2” variable. Then, call the “print()” statement:
print(df2)
It can be observed that, provided DataFrame multiple columns have been exploded successfully:
That’s all! We have explained the easiest way to explode multiple columns in Python.
Conclusion
The explode()” function is used for modifying or transforming each member of an array or element of list into rows. It convert the element of the list to a row while replacing the index values returning the DataFrame exploded element lists. This post illustrated the method to explode multiple columns in Python.