Sum based on two columns ignoring their horizontal ordering

Viewed 15

Because it is hard to describe with words I show you example data.

Initial data where you can see in row 0 and 1 the first and second columns have the same values when you ignore there horizontal order.

  Foo Bar  vals
0   A   B     4
1   B   A     5
2   C   X     2

Of course ['A', 'B'] != ['B', 'A']. But I want sorted(['A', 'B']) == sorted(['B', 'A']).

I want to group the rows by Foo and Bar but ignoring the horizontal ordering and sum(vals). The expected output could be

  Foo Bar  vals
0   A   B     9
2   C   X     2

This is an MWE generating the data.

#!/usr/bin/env python3
import pandas as pd

df = pd.DataFrame({
    'Foo': list('ABC'),
    'Bar': list('BAX'),
    'vals': [4, 5, 2],
    })

print(df)
#   Foo Bar  vals
# 0   A   B     4
# 1   B   A     5
# 2   C   X     2
0 Answers
Related