Pandas >> How to Convert a Multi-Value Column to Multiple Rows
Table of Contents
In this article, we will talk about how to split one column in which contents are concatenated with delimiter like comma to a list. And convert the list column to multiple rows with other columns duplicated.
Preparing data
import pandas as pd
df = pd.DataFrame({
"name": ["Kevin", "Jack", "Mary"],
"sex": ["M", "M", "F"],
"hobbies": ["Writing,Chess", "Drawing,Coding", "Music,Reading"]
}, index=["K", "J", "M"])
df
Use str.split() to split a column to a list
df["hobbies"] = df["hobbies"].str.split(",")
df
Convert the column with a list-type value to multiple rows
You can use explode() method of Pandas to convert a column with list-type values to multiple rows with other columns are duplicated.
df = df.explode("hobbies")
df
Conclusion
We used str.split() to split one column to a list and used explode() method to convert it to multiple rows.
For more str method, you can read the article below.
Pandas » How to Process a Whole Column Like String
https://thats-it-code.com/pandas/pandas__how-to-process-a-whole-column-like-string/