Home >Backend Development >Python Tutorial >How can I split text strings into multiple rows based on specific delimiters using Pandas?

How can I split text strings into multiple rows based on specific delimiters using Pandas?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 08:40:03404browse

How can I split text strings into multiple rows based on specific delimiters using Pandas?

Pandas Method to Split Text into Multiple Rows

Problem:
A large CSV file contains a column with text strings that need to be split into multiple rows based on specific delimiters. The goal is to create separate rows for each set of split text.

Solution using Pandas:

  1. Split the text by the first delimiter (space) using str.split(' ').
  2. Apply the apply() function to split each string in the list by the second delimiter (colon) and convert it into a series.
  3. Use stack() to transform the resulting DataFrame into a single column and reset the index.
  4. Rename the column to 'Seatblocks'.
  5. Drop the original 'Seatblocks' column from the DataFrame.
  6. Join the new 'Seatblocks' column to the original DataFrame.

Split by Space and Colon:

s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()
s.index = s.index.droplevel(-1)
s.name = 'Seatblocks'
del df['Seatblocks']
df.join(s)

Example Output:

   CustNum     CustomerName  ItemQty Item  ItemExt  Seatblocks
0    32363  McCartney, Paul        3  F04       60  2:218:10:4,6
1    31316     Lennon, John       25  F01      300  1:13:36:1,12
1    31316     Lennon, John       25  F01      300  1:13:37:1,13

Split by Colon:

df.join(s.apply(lambda x: Series(x.split(':'))))

Example Output:

   CustNum     CustomerName  ItemQty Item  ItemExt  0    1   2     3
0    32363  McCartney, Paul        3  F04       60  2  218  10   4,6
1    31316     Lennon, John       25  F01      300  1   13  36  1,12
1    31316     Lennon, John       25  F01      300  1   13  37  1,13

The above is the detailed content of How can I split text strings into multiple rows based on specific delimiters using Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn