问题
I am trying to visualize some data I got using python and bokeh, but it is not working out. It is a .csv file and it looks like this, only then with much more rows and values:
;A;B;C;DA;0;0;1;2;B;0;3;0;0;C;0;0;0;1;D;1;0;2;0
I have tried some stuff, but it did not get me far and now I am kind of stuck.
I tried to make the list with this:
import csv
with open('coauth.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
print(your_list)
But then it outputs a nested list like this:
[[';A;B;C;D'], ['A;0;0;1;2'], ['B;0;3;0;0']...
And so on.
It would be nice if the output could be something like:
{ 'A' : [0, 0, 1, 2], 'B' : [0, 3, 0, 0],... }
Does someone have an idea of how I should tackle it and maybe also an idea on how to move further with the visualization?
回答1:
You probably want to convert it to an actual matrix, using numpy
, for instance. Seems like the first list in your list of lists gives you the nodes for the columns, then the first value in each subsequent list is the node for each row. You could split each list by the ;
, then select the values that aren't the node name (A,B, etc.) and store them as a row in your matrix, so that your matrix looks like
import numpy as np
# Numpy matrix, or array of a list of lists
np.array([[0,0,1,2],
[0,3,0,0],
[0,0,0,1],
[1,0,2,0]])
Based on your comment, you could do something like
split_list = [row.split(';') for sublist in your_list for row in sublist]
your_dict = {row[0]: row[1:] for row in split_list[1:]}
#Output
{'A': ['0', '0', '1', '2'], 'B': ['0', '3', '0', '0']}
来源:https://stackoverflow.com/questions/55868466/csv-to-adjacency-matrix