1

We have a DataFrame with 2 columns as follows:

|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b','c']|  
|2    |['d','e','f','g']| 

We need to generate a combination of all list elements while duplicating the Type, as follows:

|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b']|  
|1    |['a','c']|  
|1    |['b','c']|  
|2    |['d','e']|  
|2    |['e','f']|  
.....

In order to generate the combinations we are using the following code:

import itertools
list(itertools.combinations(df.list_dates,2) )

Any suggestions?

1 Answer 1

1

I think pure python solution working best. So first create tuples by dict and then create list of tuples by combinations. Last create DataFrame by constructor:

import itertools

L = []
for x, y in zip(df['Type'], df['list_dates']):
    a = list(itertools.combinations(y,2))
    for i in a:
        L.append((x, list(i)))

Or nested list comprehension solution:

L = [(x, list(i)) for x, y in zip(df['Type'], df['list_dates']) 
                  for i in list(itertools.combinations(y,2))]

df = pd.DataFrame(L, columns=['Type','list_dates'])
print (df)

   Type list_dates
0     1     [a, b]
1     1     [a, c]
2     1     [b, c]
3     2     [d, e]
4     2     [d, f]
5     2     [d, g]
6     2     [e, f]
7     2     [e, g]
8     2     [f, g]

Thanks, piRSquared for nice suggestion - if DataFrame have only 2 columns:

import itertools

L = []
for x, y in df.values:
    a = list(itertools.combinations(y,2))
    for i in a:
        L.append((x, list(i)))

L = [(x, list(i)) for x, y in df.values for i in list(itertools.combinations(y,2))]

If more columns first filter:

L = [(x, list(i)) for x, y in df[['Type','list_dates']].values 
                  for i in list(itertools.combinations(y,2))]
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need the zip pd.DataFrame([[x, list(y)] for x, z in df.values for y in itertools.combinations(z, 2)], columns=['Type','list_dates'])
Great! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.