Search code examples
pythoncombinationspython-itertools

Python : Finding combinations in column and doing relative operations using index values


I need to find possible combinations (two pairs) in a list/column and perform a relative operation on relative column/list. Like, subtraction on values of the pairs.

Example input:

column 1 column2
----------------
A         10
C         20
B         30

Output

column1  column2    #internal operation
--------------------------------------
[A,B]    -20        A-B
[A,C]    -10        A-C
[C,B]    -10        C-B

I have used itertools.combinations for combinations.

Any tips to be get this done?


Solution

  • Put your initial columns into map P (P = {'A': 10, ..} etc.) and than just calculate w = [((c1, c2), P[c1] - P[c2]) for c1, c2 in itertools.combinations(P.keys(), 2)] . It should contain all data that you would like to put in resulting column.

    To obtain data by columns: letters_pairs, values = zip(*w)