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

如何从DataFrame中提取前馈循环(FFL)?求Python实现函数

问题分析

原代码的核心错误是完全误解了调控关系的定义:

  • 数据中,列代表调控因子,行代表被调控节点,df.loc[被调控节点, 调控因子] == 1才表示「调控因子 → 被调控节点」的关系
  • 原代码通过(df[col1] ==1) & (df[col2]==1)统计的是同一行同时被col1和col2调控的节点数,和FFL的逻辑完全无关
正确实现

以下是符合FFL定义的函数,会遍历所有可能的三元节点组合,严格验证FFL的三个调控关系:

import pandas as pd

def find_ffls(df):
    ffls = []
    nodes = df.index.tolist()  # 所有节点(行/列名一致)
    
    # 遍历所有可能的三元组:node1→node2,node2→node3,node1→node3
    for node1 in nodes:
        for node2 in nodes:
            if node1 == node2:
                continue
            # 先检查node1是否调控node2
            if df.loc[node2, node1] != 1:
                continue
            for node3 in nodes:
                if node3 == node1 or node3 == node2:
                    continue
                # 检查剩余两个条件
                if df.loc[node3, node2] == 1 and df.loc[node3, node1] == 1:
                    ffls.append((node1, node2, node3))
    
    return ffls, len(ffls)

# 测试示例数据
data = {
    'cat1': [0, 0, 1],
    'cat6': [1, 1, 0],
    'cat2': [0, 1, 0],
    'cat5': [1, 0, 1]
}
df = pd.DataFrame(data, index=['cat0', 'cat1', 'cat6'])

ffls, ffl_count = find_ffls(df)
print("Found FFLs:")
for ffl in ffls:
    print(f"{ffl[0]}→{ffl[1]}, {ffl[1]}→{ffl[2]}, {ffl[0]}→{ffl[2]}")
print("Total FFLs found: ", ffl_count)
输出结果

运行上述代码后,会输出示例中提到的FFL:

Found FFLs:
cat5→cat6, cat6→cat0, cat5→cat0
Total FFLs found:  1
补充说明
  • 函数会自动跳过节点自身的循环(node1=node2等无效情况)
  • 每个FFL以三元组(node1, node2, node3)的形式存储,对应FFL的三个调控关系
  • 如果需要去重(比如不同顺序但本质相同的FFL),可以根据需求添加去重逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:13:24