如何从pandas数据帧创建边缘列表?

Mel*_*uce 4 python dataframe pandas network-analysis

我有一个形式的熊猫数据帧(df) -

    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为边缘列表,即表单的数据框:

Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2
Run Code Online (Sandbox Code Playgroud)

编辑 请注意,新数据框的行数等于可能的成对组合的总数.此外,要计算"权重"列,我们只需找到两个列表之间的交集.例如,对于B&C,元素共享两种颜色:蓝色和黄色.因此,相应行的"权重"为2.

最快的方法是什么?原始数据框包含大约28,000个元素.

WeN*_*Ben 5

试试这个.工作不是很整洁.PS:最后输出你可以调整它,我没有删除列并更改列名称

import pandas as pd 
df=pd.DataFrame({"Col1":[['Green','Red','Purple'],['Red', 'Yellow', 'Blue'],['Brown', 'Green', 'Yellow', 'Blue']],"two":['A','B','C']})
df=df.set_index('two')
del df.index.name
from itertools import combinations
DF=pd.DataFrame()
dict1=df.T.to_dict('list')
DF=pd.DataFrame(data=[x for x in combinations(df.index, 2)])
DF['0_0']=DF[0].map(df['Col1'])
DF['1_1']=DF[1].map(df['Col1'])
DF['Weight']=DF.apply(lambda x : len(set(x['0_0']).intersection(x['1_1'])),axis=1)



DF
Out[174]: 
   0  1                   0_0                           1_1  Weight
0  A  B  [Green, Red, Purple]           [Red, Yellow, Blue]       1
1  A  C  [Green, Red, Purple]  [Brown, Green, Yellow, Blue]       1
2  B  C   [Red, Yellow, Blue]  [Brown, Green, Yellow, Blue]       2
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 5

首先,从数据帧开始:

from itertools import combinations

df = pd.DataFrame({
        'Col1': [['Green','Red','Purple'], 
                 ['Red', 'Yellow', 'Blue'], 
                 ['Brown', 'Green', 'Yellow', 'Blue']]
     }, index=['A', 'B', 'C'])

df['Col1'] = df['Col1'].apply(set)    
df

                           Col1
A          {Purple, Red, Green}
B           {Red, Blue, Yellow}
C  {Green, Yellow, Blue, Brown}
Run Code Online (Sandbox Code Playgroud)

每个列表Col1都已转换为集合以有效地找到联合.接下来,我们将用于itertools.combinations创建所有行的成对组合df:

df1 = pd.DataFrame(
    data=list(combinations(df.index.tolist(), 2)), 
    columns=['Src', 'Dst'])

df1

  Src Dst
0   A   B
1   A   C
2   B   C
Run Code Online (Sandbox Code Playgroud)

现在,应用一个函数来获取集合的并集并找到它的长度.在SrcDst列作为查找到df.

df1['Weights'] = df1.apply(lambda x: len(
    df.loc[x['Src']]['Col1'].intersection(df.loc[x['Dst']]['Col1'])), axis=1)
df1

  Src Dst  Weights
0   A   B        1
1   A   C        1
2   B   C        2
Run Code Online (Sandbox Code Playgroud)

我建议在一开始就设置转换.每次动态将列表转换为集合都是昂贵且浪费的.

为了获得更高的速度,您可能希望将这些集合复制到新数据框中的两列,就像@Wen所做的那样,因为df.loc不断调用会使速度降低一个档次.