cross join/merge to create dataframe of combinations (order doesn't matter)

独自空忆成欢 提交于 2019-12-13 06:47:21

问题


I have a dataframe that has 6 categorical/string values. I want to create a dataframe of all possible combination of these string values where order DOES NOT matter (i.e. a, b = b, a).

I did the following but I see that the result is a permutation and not a combination i.e. it distinguishes (IL, IL-1) from (IL-1, IL).

I have read through:

http://pandas.pydata.org/pandas-docs/stable/merging.html#brief-primer-on-merge-methods-relational-algebra

In mysql I can do this via:

select r1.id, r2,id 
from rows r1 
cross join rows r2 
where r1.id < r2.id

I appreciate your help.

>data = ['IL', 'IL-1', 'IL-2', 'IL-3', 'IL-4', 'IL-5']
>df = pd.DataFrame(data)
>df['key1']= pd.Series([1] * len(df))
>df2 = df.copy()
>cart = pd.merge(df, df2, on='key1')

Resulting dataframe:

0_x

key1

0_y

0
IL 1 IL 
1
IL 1 IL-1 
2
IL 1 IL-2 
3
IL 1 IL-3 
4
IL 1 IL-4 
5
IL 1 IL-5 
6
IL-1 1 IL 
7
IL-1 1 IL-1  
8
IL-1 1 IL-2    
9
IL-1 1 IL-3 
10
IL-1 1 IL-4   
11
IL-1 1 IL-5 
12
IL-2 1 IL 
13
IL-2 1 IL-1 
14
IL-2 1 IL-2 
15
IL-2 1 IL-3 
16
IL-2 1 IL-4 
17
IL-2 1 IL-5 
18
IL-3 1 IL 
19
IL-3 1 IL-1 
20
IL-3 1 IL-2 
21
IL-3 1 IL-3 
22
IL-3 1 IL-4 
23
IL-3 1 IL-5  
24
IL-4 1 IL 
25
IL-4 1 IL-1 
26
IL-4 1 IL-2 
27
IL-4 1 IL-3 
28
IL-4 1 IL-4 
29
IL-4 1 IL-5  
30
IL-5 1 IL 
31
IL-5 1 IL-1 
32
IL-5 1 IL-2 
33
IL-5 1 IL-3 
34
IL-5 1 IL-4 
35
IL-5 1 IL-5 

回答1:


Putting together what's on the comments and making a 15 row (6C2) DataFrame with the proposed index and some dummy data:

import itertools
import pandas as pd

labels = ['IL', 'IL-1', 'IL-2', 'IL-3', 'IL-4', 'IL-5']
i = pd.MultiIndex.from_tuples(list(itertools.combinations(labels, 2)))
df = pd.DataFrame({'col1':range(len(i))}, index=i)

Output:

           col1
IL   IL-1     0
     IL-2     1
     IL-3     2
     IL-4     3
     IL-5     4
IL-1 IL-2     5
     IL-3     6
     IL-4     7
     IL-5     8
IL-2 IL-3     9
     IL-4    10
     IL-5    11
IL-3 IL-4    12
     IL-5    13
IL-4 IL-5    14

In case you want all 36 combinations of a cartesian product (which I don't think is the case):

i = pd.MultiIndex.from_product([labels, labels])


来源:https://stackoverflow.com/questions/35780710/cross-join-merge-to-create-dataframe-of-combinations-order-doesnt-matter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!