0

I have a dataframe which looks like:

Origional Data

I would like to regroup the dataframe to be:

New Data

Can I do that using pd.groupby() or any other way?

  • Does this answer your question? [Pandas group-by and sum](https://stackoverflow.com/questions/39922986/pandas-group-by-and-sum) – tidakdiinginkan May 11 '20 at 20:32

1 Answers1

1

IIUC, np.sort and Groupby.sum

print(df)
  col1 col2  col3
0    A    B    10
1    C    D    15
2    B    A    15
3    D    C     3

cols = ['col1', 'col2']
new_df = (df.assign(**dict(zip(cols, np.sort(df[cols], axis=1).T)))
            .groupby(cols, as_index=False).sum())
print(new_df)
  col1 col2  col3
0    A    B    25
1    C    D    18

Or

df2 = df.copy()
df2[cols] = np.sort(df[cols], axis=1)
df2.groupby(cols, as_index=False).sum()
ansev
  • 30,322
  • 5
  • 17
  • 31