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:
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!