


How to Split Comma-Separated Strings in a Pandas DataFrame into Separate Rows?
Splitting Comma-Separated String Entries in a Pandas DataFrame to Create Separate Rows
Problem:
We have a Pandas DataFrame containing strings with comma-separated values in one column. We wish to split each CSV entry and create a new row for each unique value. For instance, "a,b,c" should become "a", "b", "c".
Solution:
Option 1: DataFrame.explode() (Pandas 0.25.0 )
The DataFrame.explode() method is specifically designed for this purpose. It allows us to split a list-like column (in this case, our comma-separated strings) into individual rows.
In [1]: df.explode('var1') Out[1]: var1 var2 var3 0 a 1 XX 1 b 1 XX 2 c 1 XX 3 d 2 ZZ 4 e 2 ZZ 5 f 2 ZZ 6 x 2 ZZ 7 y 2 ZZ
Option 2: Custom Vectorized Function
If DataFrame.explode() is not available or we need more customization, we can create our own vectorized function:
import numpy as np def explode(df, lst_cols, fill_value='', preserve_index=False): # Convert `lst_cols` to a list if it is a string. if isinstance(lst_cols, str): lst_cols = [lst_cols] # Calculate the lengths of each list in `lst_cols`. lens = df[lst_cols[0]].str.len() # Create a new index based on the lengths of the lists. idx = np.repeat(df.index.values, lens) # Create a new DataFrame with the exploded columns. exp_df = pd.DataFrame({ col: np.repeat(df[col].values, lens) for col in df.columns.difference(lst_cols) }, index=idx).assign(**{ col: np.concatenate(df.loc[lens > 0, col].values) for col in lst_cols }) # Append rows with empty lists if necessary. if (lens == 0).any(): exp_df = exp_df.append(df.loc[lens == 0, df.columns.difference(lst_cols)], sort=False).fillna(fill_value) # Revert the original index order and reset the index if requested. exp_df = exp_df.sort_index() if not preserve_index: exp_df = exp_df.reset_index(drop=True) return exp_df
Example usage:
In [2]: explode(df, 'var1') Out[2]: var1 var2 var3 0 a 1 XX 1 b 1 XX 2 c 1 XX 3 d 2 ZZ 4 e 2 ZZ 5 f 2 ZZ 6 x 2 ZZ 7 y 2 ZZ
The above is the detailed content of How to Split Comma-Separated Strings in a Pandas DataFrame into Separate Rows?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
