1

How can I achieve the expected result from the following DataFrame

 df
            col_1             col_2    col_3
     0  Non-Saved    www.google.com   20,567
     1             www.facebook.com      
     2             www.linkedin.com      
     3      Saved     www.Quora.com    6,337
     4                www.gmail.com      

Expected result:

            col_1              col_2    col_3
     0  Non-Saved     www.google.com   20,567
                    www.facebook.com
                    www.linkedin.com
     1  Saved          www.Quora.com    6,337
                       www.gmail.com   

From 5 rows to 2 rows by merging the empty strings in col_1 and col_3. Also, concatenating values in col_2 into one cell. Can anyone help me with an user-defined function to do this?

Preetesh Gaitonde
  • 449
  • 1
  • 9
  • 18

1 Answers1

2

Let's try:

df = df.apply(lambda x: x.str.strip()).replace('',np.nan)

df.groupby(df.col_1.ffill())\
  .agg({'col_2': lambda x: ' '.join(x) ,'col_3':'first'})\
  .reset_index()

Output:

       col_1                                             col_2   col_3
0  Non-Saved  www.google.com www.facebook.com www.linkedin.com  20,567
1      Saved                       www.Quora.com www.gmail.com   6,337
Scott Boston
  • 147,308
  • 15
  • 139
  • 187