Search code examples
pythonpandasnetworkx

Attribute error trying to create a dataframe that includes nodes' degree


I'd need to create a dataframe having two columns, one for nodes and the other one for their degree. I calculated the degree of each node as : d = dict(G.degree) where G is G = nx.from_pandas_edgelist(tf, 'N', 'T').

tf is

N   T 
name1 name 
name2 name1
name4 name2

...

The output from d is

{
'name1': 9,
 'name2': 1,
 'name3': 1,
 'name4': 1, ...}

I wrongly tried to convert it into a dataframe as follows

degree=pd.DataFrame.from_dict(data, orient='index', columns=['N', 'Degree'])

but I have got the error ValueError: 2 columns passed, passed data had 300 columns.


Solution

  • If I understood it correctly, you want the following

    data = {'name1': 9, 'name2': 1, 'name3': 1, 'name4': 1}
    
    df = pd.DataFrame(data.items(), columns=['N', 'Degree'])
    

    Output

    >>> df 
    
           N  Degree
    0  name1       9
    1  name2       1
    2  name3       1
    3  name4       1