module 'networkx' has no attribute 'from_pandas_dataframe'

此博客为转载内容,转载自https://www.cnblogs.com/students/p/10821402.html ,涉及Python相关知识。
使用networkx.rom_pandas_dataframe()报错:
改正:使用
networkx.from_pandas_edgelist

转载于:https://www.cnblogs.com/students/p/10821402.html

import math import sys sys.modules['fractions'] = math # 将 fractions 模块映射到 math import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cbook as cbook from collections.abc import Iterable import networkx as nx # 解决其他兼容性问题 - 移除 np.int 的引用 # np.int 已被完全移除,使用内置 int 替代 cbook.iterable = lambda x: isinstance(x, Iterable) # 解决 iterable 问题 # 修正LiNGAM的导入路径 from causallearn.search.FCMBased.lingam import ICALiNGAM # 生成示例数据 np.random.seed(42) n_samples = 50 # 样本数 A = np.random.normal(size=n_samples) B = 0.5 * A + np.random.normal(size=n_samples) C = 0.3 * A + np.random.normal(size=n_samples) D = 0.2 * B + 0.4 * C + np.random.normal(size=n_samples) data = pd.DataFrame({'A': A, 'B': B, 'C': C, 'D': D}) print("示例数据:") print(data.head()) # 使用 LiNGAM 算法推断因果结构 model = ICALiNGAM() model.fit(data.values) # 获取邻接矩阵 adjacency_matrix = model.adjacency_matrix_ # 转换为 NetworkX 图 G = nx.DiGraph() nodes = data.columns.tolist() G.add_nodes_from(nodes) # 添加推断的有向边(仅保留显著连接) threshold = 0.3 # 调整阈值以减少噪声边 for i, cause in enumerate(nodes): for j, effect in enumerate(nodes): if abs(adjacency_matrix[i, j]) > threshold: G.add_edge(cause, effect, weight=round(adjacency_matrix[i, j], 2)) # 尝试不同的matplotlib后端 try: plt.switch_backend('Agg') # 切换到Agg后端,适合非交互式环境 except: pass # 如果切换失败则使用默认后端 # 可视化因果关系图 - 使用更简单的绘制方式 plt.figure(figsize=(8, 6)) pos = nx.spring_layout(G, seed=42) # 绘制节点和边 nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=2000) nx.draw_networkx_labels(G, pos, font_size=12) nx.draw_networkx_edges(G, pos, arrowsize=20, arrowstyle='->', edge_color='gray') # 添加边权重标签 edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10) plt.title("Automatically Inferred Causal Diagram", fontsize=14) plt.axis('off') # 尝试不同的显示方式 try: plt.tight_layout() plt.show() except Exception as e: print(f"显示图形时出错: {e}") # 保存图形到文件作为备选方案 plt.savefig('causal_diagram.png', dpi=300, bbox_inches='tight') print("图形已保存为 'causal_diagram.png'")修改代码,解决报错Traceback (most recent call last): File "c:\Users\mwj19\Desktop\econ.py", line 10, in <module> import networkx as nx File "D:\anaconda3\envs\tensorflow\lib\site-packages\networkx\__init__.py", line 117, in <module> import networkx.readwrite File "D:\anaconda3\envs\tensorflow\lib\site-packages\networkx\readwrite\__init__.py", line 15, in <module> from networkx.readwrite.graphml import * File "D:\anaconda3\envs\tensorflow\lib\site-packages\networkx\readwrite\graphml.py", line 314, in <module> class GraphML(object): File "D:\anaconda3\envs\tensorflow\lib\site-packages\networkx\readwrite\graphml.py", line 346, in GraphML (np.int, "int"), (np.int8, "int"), File "D:\anaconda3\envs\tensorflow\lib\site-packages\numpy\__init__.py", line 353, in __getattr__ raise AttributeError(__former_attrs__[attr]) AttributeError: module 'numpy' has no attribute 'int'. `np.int` was a deprecated alias for the builtin `int`. To avoid this error in existing code, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information. The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations ERROR conda.cli.main_run:execute(125): `conda run python c:/Users/mwj19/Desktop/econ.py` failed. (See above for error)
最新发布
08-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值