gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:23 26 4
gpt4 key购买 nike

我有以下数据框:

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)

欢迎任何帮助。

最佳答案

在这里,我没有使用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

关于python - 根据pandas数据框的列值使用networkx创建图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com