data1 = { 'node1': [1,1,1,2],
'node2': [2,3,5,4],
'weight': [1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
data2 = { 'node1': [1,1,2,3],
'node2': [4,5,4,5],
'weight': [1,1,1,1], }
df2= pd.DataFrame(data2, columns = ['node1','node2','weight'])
Expected Output:
0 0 0 1 0
0 0 0 0 0
0 0 0 0 1
1 0 0 0 0
0 0 1 0 0
我想创建一个矩阵,矩阵中的1表示在第二个数据帧中形成的新行。例如,2 4是一个在两个数据帧中的行,因此在矩阵中我们将矩阵[2,4] = 0和[4,2] = 0作为关系是双向的。
2)1 4是第二个数据帧中的一个新行,它不在第一个数据帧中,所以我们把矩阵[1,4] = 1和[4,1] = 1
3)如果组合在dfs中看起来不像[3,4]那么它的矩阵[3,4] =矩阵[4,3] = 0
此外,由于这是一个代表性数据集,而我的真实数据集非常庞大,因此稀疏表示需要。
答案 0 :(得分:1)
对所有1
0
使用merge
df = df2.merge(df1, 'outer', indicator=True).query("_merge=='left_only'")
print (df)
node1 node2 weight _merge
0 1 4 1 left_only
3 3 5 1 left_only
df3 = df.set_index(['node1','node2'])['weight'].unstack().notnull().astype(int)
df3 = df3.mul(df3.T, fill_value=1)
cols = ['node1','node2']
min1 = df1[cols].values.min()
max1 = df1[cols].values.max()
min2 = df2[cols].values.min()
max2 = df2[cols].values.max()
a = range(min(min1,min2), max(max1, max2) + 1)
df3 = df3.reindex(index=a, columns=a).fillna(0).astype(int)
print (df3)
1 2 3 4 5
1 0 0 0 1 0
2 0 0 0 0 0
3 0 0 0 0 1
4 1 0 0 0 0
5 0 0 1 0 0
值reindex
:
i