Combination of pair elements within lists in a DataFrame

Viewed 507

I'm trying to obtain the pair combinations of elements (list elements) within a DataFrame. I need to keep the first column to determine the original 'group' of the element pairs but splitting the element lists into element pairs in new rows.

I would have the following case:

Group X
0 Group 1 A,B,C
1 Group 2 D,E
2 Group 3 F,G,H,I

And the output needs to be something like:

Group X
0 Group 1 A,B
1 Group 1 A,C
2 Group 1 B,C
3 Group 2 D,E
4 Group 3 F,G
5 Group 3 F,H
6 Group 3 F,I
7 Group 3 G,H
8 Group 3 G,I
9 Group 3 H,I

I would like to keep the Group column belonging to every combination. I don't know how to iterate through a DataFrame and keep that Group values in each row.

2 Answers

Use itertools.combinations to find all combinations of elements of length 2 for each row in the dataframe. This will give you a list exploded using explode as follows:

from itertools import combinations

df['X'] = df['X'].apply(lambda l: list(combinations(l, 2)))
df = df.explode('X')

Result:

     Group    X
0  Group 1  A,B
0  Group 1  A,C
0  Group 1  B,C
1  Group 2  D,E
2  Group 3  F,G
2  Group 3  F,H
2  Group 3  F,I
2  Group 3  G,H
2  Group 3  G,I
2  Group 3  H,I

Shaido’s answer is great, but I want to add something

    1. create a toy dataset

import pandas as pd 
import numpy as np 
import itertools
basedata = pd.DataFrame({"Group":['Group1', 'Group2', 'Group3'],
"x":['A,B,C', 'D,E', 'F,G,H,I']})
basedata

enter image description here

    1. split character by ","
basedata['x'] = basedata['x'].apply(lambda x: x.split(','))
basedata

enter image description here

  • 3.use itertools generate combinations
basedata['x'] = basedata['x'].apply(lambda x: list(itertools.combinations(x, 2)))
basedata

enter image description here

    1. use pandas explode function to explode "x"
basedata = basedata.explode("x")
basedata

enter image description here

  • 5 transform set to character
basedata['x'] = basedata['x'].apply(lambda x: ','.join(x))
basedata

enter image description here

get more information,you can click those links:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html

https://docs.python.org/3/library/itertools.html#itertools.combinations

Related