python - 寻找树内最近的节点

标签 python pandas search tree

我有一个 pandas.DataFrame 包含树中的节点。该表如下所示:

╔═══════╦════════╦════════╦══════╗
║ index ║ color  ║  name  ║ head ║
╠═══════╬════════╬════════╬══════╣
║     0 ║ red    ║ Tom    ║    0 ║
║     1 ║ blue   ║ Lucy   ║    0 ║
║     2 ║ green  ║ Peter  ║    1 ║
║     3 ║ red    ║ Katy   ║    1 ║
║     4 ║ green  ║ Sam    ║    4 ║
║     5 ║ orange ║ Linda  ║    2 ║
║     6 ║ blue   ║ Robert ║    4 ║
║     7 ║ brown  ║ James  ║    6 ║
║     8 ║ red    ║ Betty  ║    7 ║
║     9 ║ red    ║ Amanda ║    4 ║
║    10 ║ black  ║ Luke   ║    8 ║
╚═══════╩════════╩════════╩══════╝

head存储父节点的索引。它将创建一棵树,如下所示:

Tree Structure

并且每个节点可以有0+个子节点(不限于2个)。

当我选择一个人时,我想找到另一个具有相同颜色的人。有 3 条规则:

  1. 如果在同一个词干上,则选择最近的人
  2. 如果没有选择任何人,请选择同一棵树中最近的人
  3. 如果无法选择任何人,则返回None

例如,凯蒂将与汤姆匹配。由于与 Betty 的同一茎不再有红色,因此将选择 Amanda。

除了暴力破解之外,还有什么方法可以得到答案吗?

最佳答案

我使用了网络分析技术,不确定它是否最适合您的情况。

这个想法很简单:

  1. 制作网络图
  2. 找到与您所选人员颜色相同的所有其他人,我将其称为候选人
  3. 检查候选人和所选人员在网络中是否连接(即候选人和所选人员之间是否存在路径)
  4. 找到最短路径的候选者

这是我的代码

import io
import pandas as pd
import networkx as nx
from networkx.algorithms import shortest_path, has_path


# Data
df_str = """
index,colour,name,head
0,red,Tom,0
1,blue,Lucy,0
2,green,Peter,1
3,red,Katy,1
4,green,Sam,4
5,orange,Linda,2
6,blue,Robert,4
7,brown,James,6
8,red,Betty,7
9,red,Amanda,4
10,black,Luke,8
"""
df = pd.read_csv(io.StringIO(df_str), sep=",")


# Function to find the closest person with the same colour as the person with `id0`
def find_same_colour(id0, df):
    # Create network
    g = nx.Graph()
    for _, row in df.iterrows():
        g.add_node(row['index'], colour=row['colour'])
        if row['index'] != row['head']:
            g.add_edge(row['index'], row['head'])
    # List out candidates
    colour = df.loc[df['index'].values == id0, 'colour'].values[0]
    candidates = df.loc[(df['colour'].values == colour) & (df['index'].values != id0), 'index'].values
    # Initialise searching
    target = None
    l_max = df.shape[0] + 2
    # Search
    for i in candidates:
        if has_path(g, id0, i):
            path = shortest_path(g, id0, i)
            if len(path) < l_max:
                target = i
    return target


for i in df['index'].values:
    print(i, find_same_colour(i, df), sep='-')

这是输出,

# 0-3
# 1-None
# 2-None
# 3-0
# 4-None
# 5-None
# 6-None
# 7-None
# 8-9
# 9-8
# 10-None

关于python - 寻找树内最近的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210375/

相关文章:

python - Numpy CSV fromfile()

python - 在Python中将树结构转换为csv的最有效方法的研究

python - 接下来 N 个元素(包括当前元素)的滚动总和

search - elasticsearch:如果数组字段中至少有一个元素属于范围,则使用条件进行搜索

c# - AD PrincipalSearcher : Search where property does not contain some value

python - 本地数据库上的 Firebird 连接在 Python 脚本中是不可能的

python - python中的多级字典

python-3.x - Python 3 pandas 数据框创建取决于文件格式 csv 或 txt

python - 取 nlargest 5 并对 pandas 中的其余部分求和/计数

search - Elasticsearch每个groupId的聚合唯一属性