Pandas 从列中的列表生成组合

Pandas 从列中的列表生成组合,pandas,Pandas,我们有一个包含两列的数据框架,如下所示: |Type |list_dates | |:----:|:-----------:| |1 |['a','b','c']| |2 |['d','e','f','g']| |Type |list_dates | |:----:|:-----------:| |1 |['a','b']| |1 |['a','c']| |1 |['b','c']| |2 |['d','e']|

我们有一个包含两列的数据框架,如下所示:

|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b','c']|  
|2    |['d','e','f','g']| 
|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b']|  
|1    |['a','c']|  
|1    |['b','c']|  
|2    |['d','e']|  
|2    |['e','f']|  
.....
复制类型时,我们需要生成所有列表元素的组合,如下所示:

|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b','c']|  
|2    |['d','e','f','g']| 
|Type   |list_dates  |  
|:----:|:-----------:|  
|1    |['a','b']|  
|1    |['a','c']|  
|1    |['b','c']|  
|2    |['d','e']|  
|2    |['e','f']|  
.....
为了生成组合,我们使用以下代码:

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

有什么建议吗?

我认为纯python解决方案效果最好。 因此,首先通过
dict
创建元组,然后通过组合创建
元组列表。上次按构造函数创建数据帧:

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)))
或嵌套的
列表理解
解决方案:

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]
感谢您的建议-如果
DataFrame
只有
2列

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))]
如果第一个过滤器中有更多列:

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

您不需要使用
zip
pd.DataFrame([[x,list(y)]表示x,z在df中,y在itertools.compositions(z,2)]中的值,列=['Type','list_dates'))
太好了!非常感谢。