根据pandas数据框的列值使用networkx创建图

时间:2019-05-16 13:12:41

标签: python pandas networkx

我有以下DataFrame:

import pandas as pd
df = pd.DataFrame({'id_emp': [1,2,3,4,1], 
               'name_emp': ['x','y','z','w','x'], 
               'donnated_value':[1100,11000,500,300,1000],
               'refound_value':[22000,22000,50000,450,90]
            })
df['return_percentagem'] = 100 * 
df['refound_value']/df['donnated_value']
df['classification_roi'] = ''

def comunidade(i):

    if i < 50:
        return 'Bad Investment'
    elif i >=50 and i < 100:
        return 'Median Investment'
    elif i >= 100:
        return 'Good Investment'

df['classification_roi'] = df['return_percentagem'].map(comunidade)
df

节点将是“ id_emp”。如果两个节点具有相同的“ id_emp”,但在“ classification_roi”列中具有不同的分类,或者在“ classification_roi”列中具有相同的等级,则将存在连接。简而言之,如果节点具有相同的ID或“ classification_roi”列中的分类相同,则它们具有连接。

我对networkx并没有太多练习,而我正在尝试的东西远非理想:

import networkx as nx
G = nx.from_pandas_edgelist(df, 'id_emp', 'return_percentagem')
nx.draw(G, with_labels=True)

欢迎所有帮助。

1 个答案:

答案 0 :(得分:0)

在这里,我没有使用from_pandas_edgelist。相反,请列出理解和for循环:

import matplotlib.pyplot as plt
import networkx as nx
import itertools

G = nx.Graph()

# use index to name nodes, rather than id_emp, otherwise
# multiple nodes would end up having the same name
G.add_nodes_from([a for a in df.index])

#create edges:
#same employee edges
for ie in set(df['id_emp']):
    indices = df[df['id_emp']==ie].index
    G.add_edges_from(itertools.product(indices,indices))

# same classification edges
for cr in set(df['classification_roi']):
    indices = df[df['classification_roi']==cr].index
    G.add_edges_from(itertools.product(indices,indices))

nx.draw(G)
plt.show()

enter image description here

可选:着色,以区分节点。

plt.subplot(121)
plt.title('coloured by id_emp')
nx.draw(G, node_color=df['id_emp'], cmap='viridis')

plt.subplot(122)

color_mapping = { 
    'Bad Investment': 0,
    'Median Investment': 1,
    'Good Investment':2}

plt.title('coloured by classification_roi')
nx.draw(G, node_color=df['classification_roi'].replace(color_mapping), cmap='RdYlBu')

enter image description here