You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python igraph将R的图中心性集中化计算代码转写?

将R的igraph中心性集中化值计算代码转换为Python代码

你需要把一段R代码转换为Python(基于igraph库),原代码的核心是计算mygraphs字典中各图的度中心性集中化值、介数中心性集中化值、接近中心性集中化值、特征向量中心性集中化值,最终合并为一个DataFrame。

原R代码

df_score <- do.call(rbind, lapply(mygraphs, function(gr){
    gr_deg <- centr_degree(gr)$centralization
    gr_bet <- centr_betw(gr, directed = FALSE)$centralization
    gr_clo <- centr_clo(gr, mode = "all")$centralization
    gr_eig <- centr_eigen(gr)$centralization

    #collect results in a data frame:
    df <- data.frame(betweenness=gr_bet, degree=gr_deg, closeness = gr_clo, eigen = gr_eig)
  })
)

图字典定义

# Define a dictionary of graphs
mygraphs = {"full": gr_full,
            "tree": gr_tree,
            "rnd_25": gr_rnd_25,
            "rnd_50": gr_rnd_50,
            "rnd_75": gr_rnd_75,
            "rnd_100": gr_rnd_100,
            "rnd_200": gr_rnd_200}

期望输出格式

betweenness     degree   closeness     eigen
full    0.000000000 0.00000000 0.000000000 0.0000000
tree    0.599364080 0.02040404 0.235329206 0.7833769
rnd_25  0.001588759 0.02525253 0.000855427 0.9830214
rnd_50  0.027237954 0.04040404 0.003657573 0.9509750
rnd_75  0.125037220 0.04545455 0.009697238 0.9500023
rnd_100 0.260428791 0.04040404 0.027089542 0.8168838
rnd_200 0.072028210 0.05050505 0.064183952 0.6617146

你的现有代码问题

你当前写的Python代码只计算了每个图中单个节点的度值,完全没有实现原R代码中计算整个图的中心性集中化值的逻辑。集中化值是衡量图中节点中心性分布集中程度的全局指标,和单个节点的中心性值不是一回事。

正确的Python实现代码

import pandas as pd
import igraph

# 假设mygraphs是已定义好的igraph.Graph对象字典
results = []

for graph_name, graph in mygraphs.items():
    # 对应R的centr_degree(gr)$centralization
    degree_centr = graph.degree_centralization()
    # 对应R的centr_betw(gr, directed=FALSE)$centralization
    betweenness_centr = graph.betweenness_centralization(directed=False)
    # 对应R的centr_clo(gr, mode="all")$centralization
    closeness_centr = graph.closeness_centralization(mode="all")
    # 对应R的centr_eigen(gr)$centralization
    eigen_centr = graph.eigenvector_centralization()
    
    # 收集当前图的所有集中化值
    results.append({
        "graph": graph_name,
        "betweenness": betweenness_centr,
        "degree": degree_centr,
        "closeness": closeness_centr,
        "eigen": eigen_centr
    })

# 转换为DataFrame并设置graph列为索引,匹配期望格式
df_score = pd.DataFrame(results).set_index("graph")
# 打印结果
print(df_score)

这段代码会输出和你期望格式一致的结果,每行对应一个图,列是四种中心性的集中化值。

内容的提问来源于stack exchange,提问作者Pragya Kapoor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 14:47:27