Mike Johnson Jr Mike Johnson Jr - 2 months ago 6
Python Question

Merging rows in pandas

Say I have a dataframe that looks something like this

Line VarA VarB
345 Something abc
346 Something2 def
347 Something ghi
348 Something2 jkl
349 Something mno
350 Something2 pqr
351 Something stu
352 Something2 vwx


How can I turn this dataframe into something that looks like this:

VarA VarB
Something abcghimnostu
Something2 defjklpqrvwx

Answer

You can just groupby and sum

print(df.groupby('VarA')['VarB'].sum())
VarA
something     abcghimnostu
something2    defjklpqrvwx
Name: VarB, dtype: object