Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting singular row by ";;" into multiple separate rows in same column

Currently I am in the middle of trying to split the first row whenever ';;' appears, into a new row located in the Material Description column. The code that led up to this point was:

df.loc[df['mask'] == True, ['Material Description']] = ';;' + df['Material Description']
df['Material Description'] = df['Material Description'].str.cat()
df['Material Description'].tolist()
df['Material Description'].str.split(';;') 

A code I have tried is the manipulation of this one but I cannot seem to work this out.

pd.concat([Series(row['var2'], row['var1'].split(','))
            for _, row in a.iterrows()]).reset_index()
        Material Description
0       Hello;; How are you doing;; This is good   
1
2

for desired output:

        Material Description
0       Hello
1       How are you doing
2       This is good
like image 963
Jaden-Dz99 Avatar asked Aug 24 '26 02:08

Jaden-Dz99


2 Answers

This should split the rows like your output:

df['Material Description'].apply(lambda x: x.split(';;')).explode().reset_index().drop(columns='index') 

output:

  Material Description
0                Hello
1    How are you doing
2        This is good
like image 165
oppressionslayer Avatar answered Aug 26 '26 14:08

oppressionslayer


You can change:

df['Material Description'].str.split(';;') 

to:

df1 = (df['Material Description'].str.split(';;', expand=True)
                                 .stack()
                                 .reset_index(drop=True)
                                 .to_frame('Material Description'))
print (df1)
  Material Description
0                Hello
1    How are you doing
2         This is good

Explanation:

If add expand=True to Series.str.split get DataFrame, then reshape by DataFrame.stack and last some data cleaning by DataFrame.reset_index and for one column DataFrame use Series.to_frame

like image 41
jezrael Avatar answered Aug 26 '26 16:08

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!