Assume dataset:
import pandas as pd
df = pd.DataFrame(data={
"txn": [1,1,1,2,3,3],
"person": ["a", "b", "c", "c", "d", "e"],
})
Group by transactions to get persons involved in it:
df_grp = df.groupby("txn").agg(person_list=("person", list))
>> person_list
>> txn
>> 1 [a, b, c]
>> 2 [c]
>> 3 [d, e]
Create pair combinations from person list:
import itertools
df_grp["combinations"] = df_grp.apply(lambda row: list(itertools.combinations(row["person_list"], 2)), axis=1)
>> person_list combinations
>> txn
>> 1 [a, b, c] [(a, b), (a, c), (b, c)]
>> 2 [c] []
>> 3 [d, e] [(d, e)]
Move combinations to individual rows:
df_expl = df_grp[["combinations"]].explode("combinations").dropna().reset_index()
>> txn combinations
>> 0 1 (a, b)
>> 1 1 (a, c)
>> 2 1 (b, c)
>> 3 3 (d, e)
Split person pair to individual columns:
df_expl["A"] = df_expl.apply(lambda row: row["combinations"][0], axis=1)
df_expl["B"] = df_expl.apply(lambda row: row["combinations"][1], axis=1)
>> txn A B
>> 0 1 a b
>> 1 1 a c
>> 2 1 b c
>> 3 3 d e