Skip to content Skip to sidebar Skip to footer

Concatenate Rows Column-wise In Python Pandas With Groupby

Instead of e.g. calculating the sum with group_by I would like to concatenate all rows within the same group. Instead of sum() the code beneath should just combine/ concat the rows

Solution 1:

You could try:

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Pool': ['a', 'a', 'b', 'b', 'c'], 'B':[1, 2, 3, 4, 5], 'C':[1,2,3,4,5]})
gd = df1.groupby('Pool')

def comb2(x):
    rslt = dict()
    for col in x.columns:
        rslt[col]=x[col].tolist()
    return pd.Series(rslt)

rslt = gd.apply(comb2)
rslt = rslt.drop('Pool', axis=1)
finaldf = pd.DataFrame()
for col in rslt.columns:
    tempdf = rslt[col].apply(lambda x: pd.Series(x))
    tempdf.columns  = [col+str(i+1) for i in range(len(tempdf.columns))]
    finaldf = pd.concat([finaldf, tempdf],axis=1)

print(finaldf)

Output:
      B1  B2  C1  C2
Pool                
a      1   2   1   2
b      3   4   3   4
c      5 NaN   5 NaN

Post a Comment for "Concatenate Rows Column-wise In Python Pandas With Groupby"