[Solved] Is there any pandas function to merge 3 rows?


Let’s take the following sample DataFrame, containing 2 groups
of 3 adjacent rows:

      C1   C2   C3   C4   C5   C6
ABC  NaN  NaN  NaN  NaN   PK   KJ
PQR  NaN  NaN   RR   SS  NaN  NaN
MNO   PO   UI  NaN  NaN  NaN  NaN
XXX   AA  NaN  NaN  NaN   EE  NaN
XX1  NaN   BB  NaN   DD  NaN  FF1
XX2  NaN  NaN   CC  NaN  NaN  FF2

Then proceed as follows:

  1. Define a function “cumulating” the content from a group
    of rows:

    def getFirstValue(grp):
        return grp.reset_index().bfill(axis=0).iloc[0]
    
  2. Then apply it:

    df2 = df.groupby(np.arange(len(df.index)) // 3).apply(getFirstValue)
    
  3. And a couple of “finishing” operations:

    df2.set_index('index', inplace=True)
    df2.index.name = None
    df2.columns.name = None
    

The result is:

     C1  C2  C3  C4  C5   C6
ABC  PO  UI  RR  SS  PK   KJ
XXX  AA  BB  CC  DD  EE  FF1

solved Is there any pandas function to merge 3 rows?