1

How can I achieve the expected result from the following DataFrame

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

Expected result:

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

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

Preetesh Gaitonde
  • 449
  • 1
  • 9
  • 18

1 Answers1

1

If the previous solution worked, then let's try this one:

l = lambda x: ' , '.join(x.unique())

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

print(df.groupby(df.col_1.ffill())\
  .agg({'col_2': l,'col_3': l, 'col_4':'first'})\
  .reset_index())

Output:

       col_1                                              col_2  \
0  Non-Saved  www.google.com , www.facebook.com , www.linked...   
1      Saved                      www.Quora.com , www.gmail.com   

                col_3   col_4  
0  POST , GET , OTHER  20,567  
1          POST , GET   6,337  
Scott Boston
  • 147,308
  • 15
  • 139
  • 187