【问题标题】:Grouping all connected nodes of a dataset对数据集的所有连接节点进行分组
【发布时间】:2019-06-20 12:40:13
【问题描述】:

这不是重复的:

Fastest way to perform complex search on pandas dataframe

注意:pandas 版本 0.23.4

假设:数据可以按任何顺序排列。

我有一个清单:

L = ['A', 'B', 'C', 'D', 'L', 'M', 'N', 'O']

我也有一个数据框。 Col1 和 Col2 有几个相关的列,其中包含我希望保留的相关信息。信息随意,我没有填写。

Col1  Col2  Col1Info  Col2Info  Col1moreInfo  Col2moreInfo
 A     B       x         x            x             x
 B     C
 D     C
 L     M
 M     N
 N     O

我正在尝试对列表中的每个元素执行“搜索和分组”。例如,如果我们对列表中的元素“D”执行搜索,则会返回以下组。

To    From  Col1Info  Col2Info  Col1moreInfo  Col2moreInfo
 A     B       x         x            x             x
 B     C
 D     C

我一直在玩networkx,但它是一个非常复杂的包。

【问题讨论】:

  • 你听说过union-find问题吗?
  • 您的列表L 和 df 的相关性如何?你如何得出你得到的结果?您尝试过的 networkX 的复杂代码在哪里,但不起作用?这段代码有什么问题?
  • @PatrickArtner 此列表包含我想要“分组”的所有元素。我的想法是一旦我得到一个组,我会从列表中删除该组的所有元素并继续前进。

标签: python pandas


【解决方案1】:

您可以使用两列中的值作为边来定义图形,然后查找connected_components。这是使用NetworkX的一种方式:

import networkx as nx

G=nx.Graph()
G.add_edges_from(df.values.tolist())
cc = list(nx.connected_components(G))
# [{'A', 'B', 'C', 'D'}, {'L', 'M', 'N', 'O'}]

现在假设你想通过D过滤,你可以这样做:

component = next(i for i in cc if 'B' in i)
# {'A', 'B', 'C', 'D'}

并索引两列的值都在component中的数据框:

df[df.isin(component).all(1)]

   Col1 Col2
0    A    B
1    B    C
2    D    C

通过生成数据框列表,可以将上述内容扩展到列表中的所有项目。然后我们只需使用给定项目在L 中的位置进行索引:

L = ['A', 'B', 'C', 'D', 'L', 'M', 'N', 'O']

dfs = [df[df.isin(i).all(1)] for j in L for i in cc if j in i]
print(dfs[L.index('D')])

   Col1 Col2
0    A    B
1    B    C
2    D    C

print(dfs[L.index('L')])

   Col1 Col2
3    L    M
4    M    N
5    N    O

【讨论】:

  • 行G.add_edges_from(df.values.tolist())....在我的情况下,列多于两列。可以只选择我想要的吗?类似G.add_edges_from(df['Col1','Col2'].tolist())?
  • 是的@MaxB 使用df[['Col1','Col2']](带有列表的索引)
  • 我觉得我的熊猫版本让我很伤心。它给了我以下错误'DataFrame' object has no attribute 'tolist'
  • 你需要df[['Col1','Col2']].values.tolist()@MaxB
  • 抱歉一直有麻烦...dfs = [df[df.isin(i).all(1)] for j in L for i in cc if j in i] 引发以下类型错误:unhashable type: 'dict'
猜你喜欢
  • 2018-06-18
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 2018-05-21
  • 2023-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多