Search code examples
python-3.xmatrixadjacency-matrix

Create a matrix of consecutive items in a list in Python


I have a list of players and I am trying to find a matrix of pairwise occurrence of these players.

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

I tried making a list of source, targets, and weights to form a data frame and use the concept of adjacency matrix in order to create my desired matrix.

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']])

So to create my desired matrix, I tried a couple of things like,

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

This does give me a matrix but fail to add the occurrence of duplicate pairs.


Solution

  • Remove the unique line:

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

    and should be good. You do not want to remove the duplicates there.