简体   繁体   中英

CSV file in Python to create graph and average degree

I have a CSV file with two columns assigned as nodes interacting with each other, now I want to call this file in Python to create a graph and to find out the average degree of each node.

My data looks like:

在此处输入图片说明

Next time at least put your data in text form.

Here is the data I used.

column1  column2
abc      def
abc      ghi
jkl      <empty>

In the code below I read the file some_data.csv with the csv package. I set the delimiter in the csv.reader command with delimiter=' ' . In the same command I used skipinitialspace=True to ignore extra spaces.

If both nodes are present I add the edge to the graph with add_edge , else I only add the first node with add_node . You could add another elif to test if the first node is <empty> .

import networkx as nx
import csv

G = nx.Graph()

with open('some_data.csv') as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        next(csv_reader, None)  # skip header
        for row in csv_reader:
            # check if second node is empty
            if row[1] == '<empty>':
                G.add_node(row[0])
            # else assume both nodes are present
            else:
                G.add_edge(row[0], row[1])

You can get the individual nodes with nodes . To get their degrees you can use degree .

for node in G.nodes():
    print(node, 'has a degree of', G.degree(node))

Output:

jkl has a degree of 0
def has a degree of 1
ghi has a degree of 1
abc has a degree of 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM