Reputation: 3
I have a dataframe which looks like:
I would like to regroup the dataframe to be:
Can I do that using pd.groupby() or any other way?
Upvotes: 0
Views: 32
Reputation: 30920
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()
Upvotes: 1