求并流d之间的关系

2024-05-15 21:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个看起来像图形数据库的数据帧。你知道吗

import pandas as pd
mycols=['china', 'england', 'france', 'india', 'pakistan', 'taiwan']

df=pd.DataFrame([[0, 0, 0, 3, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 1, 0, 1, 0, 0],
       [3, 1, 1, 0, 1, 0],
       [0, 0, 0, 1, 0, 4],
       [0, 0, 0, 0, 4, 0]], columns=mycols)

df.index=mycols

简化的虚拟数据帧如下所示:

           china    england france  india   pakistan    taiwan
china          0          0      0      3          0    0
england        0          0      1      1          0    0
france         0          1      0      1          0    0
india          3          1      1      0          1    0
pakistan       0          0      0      1          0    4
taiwan         0          0      0      0          4    0

假设一个用户想从中国到印度,有一条直接的路线。你知道吗

df[df['china'] > 0].index.str.contains('india')
array([ True])

但没有直达英国的路线:

df[df['china'] > 0].index.str.contains('england')
array([False])

在这种情况下,我需要找到共同的国家:

set(df[df.loc['china'] > 0].index.values) & set(df[df.loc['england'] > 0].index.values)
{'india'}

但有些情况下,没有共同的朋友,我需要找到朋友的朋友到达目的地。例如

set(df[df.loc['china'] > 0].index.values) & set(df[df.loc['taiwan'] > 0].index.values)

1)在这种情况下,如何编写返回中国-印度-巴基斯坦-台湾的查询?你知道吗

2)有没有更好的储存方法?或者SQL-like(行/列)可以吗?你知道吗


Tags: 数据dfindex情况朋友locvaluesset
2条回答

你的问题(我假设)基本上是找到加权图中任意两个给定节点之间的最短路径。从算法上讲,这被称为Shortest path problem(或者更准确地说是单对最短路径问题)。networkx2.1有一个函数^{}来实现这一点

从他们的例子来看

G = nx.path_graph(5)
>>> print(nx.shortest_path(G, source=0, target=4))
[0, 1, 2, 3, 4]

If the source and target are both specified, return a single list of nodes in a shortest path from the source to the target.

如果您想从一个源获取到所有节点的最短路径,只需跳过target节点(本质上是一个单源最短路径问题)

您可以通过以下方式使用Networkx实现这一点

加载图形

import pandas as pd
import networkx as nx
mycols=['china', 'england', 'france', 'india', 'pakistan', 'taiwan']

df=pd.DataFrame([[0, 0, 0, 3, 0, 0],
   [0, 0, 1, 1, 0, 0],
   [0, 1, 0, 1, 0, 0],
   [3, 1, 1, 0, 1, 0],
   [0, 0, 0, 1, 0, 4],
   [0, 0, 0, 0, 4, 0]], columns=mycols)

#Load the graph from dataframe
G = nx.from_numpy_matrix(df.values)

#set the nodes names
G = nx.relabel_nodes(graph, dict(enumerate(mycols)))

测试图形是否正确加载

print G.edges()
#EdgeView([('pakistan', 'taiwan'), ('pakistan', 'india'), ('england', 'india'), ('england', 'france'), ('india', 'china'), ('india', 'france')])

print graph['china']
#AtlasView({'india': {'weight': 3}})

print graph['england']
#AtlasView({'india': {'weight': 1}, 'france': {'weight': 1}})

现在假设您需要找到从chinaindia的所有路径

for path in nx.all_simple_paths(graph, source='china', target='taiwan'):
    print path
#Output : ['china', 'india', 'pakistan', 'taiwan']

如果您想找到从一个节点到另一个节点的最短路径

for path in nx.all_shortest_paths(graph, source='taiwan', target='india'):
    print path
#Output : ['taiwan', 'pakistan', 'india']

您可以找到多种其他算法来查找短文本路径、全对最短路径、dijsktra算法等at their documentation以适合您的查询

注意可能存在一种使用from_pandas_dataframe直接从pandas加载图形的方法,但是我不确定用例是否正确,因为它需要一个源和目标

相关问题 更多 >