在 Python 中的列表中创建连续项目的矩阵

Create a matrix of consecutive items in a list in Python

我有一个玩家列表,我正在尝试找到这些玩家成对出现的矩阵。

players = [Player52, Player48,Player41,Player42,Player52,Player48]
matrix = 
          Player52  Player48  Player41  Player42
Player52      0         2        0          0
Player48      0         0        1          0
Player41      0         0        0          1
Player42      1         0        0          0

我尝试列出源、目标和权重以形成数据框,并使用邻接矩阵的概念来创建我想要的矩阵。

import json
import pandas as pd
import numpy as np
with open('interactions_clean.json') as f:
    data = json.load(f)

for i in data:
    player_list.append(i['dataItem']['Name'])

first = []
second =[]
for i in range(len(players) - 1):
    first.append(players[i])
    second.append(players[i+1])

weight = [1]*684

matrix_ad = pd.DataFrame({'source': first, "target": second, 'weight': weight})
vals = np.unique(matrix_ad[['source', 'target']])

因此,为了创建我想要的矩阵,我尝试了一些方法,例如,

x= matrix_ad.pivot_table(index='source',columns='target',values='weight')

这确实给了我一个矩阵,但没有添加重复对的出现。

删除唯一行:

vals = np.unique(matrix_ad[['source', 'target']])

而且应该不错。您不想删除那里的重复项。