Skip to content Skip to sidebar Skip to footer

Combining Rows In Pandas Dataframe By Iterating

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

Solution 1:

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

Post a Comment for "Combining Rows In Pandas Dataframe By Iterating"