gpt4 book ai didi

python - 对 Pandas 数据框执行复杂搜索的最快方法

转载 作者:太空狗 更新时间:2023-10-29 17:05:11 26 4
gpt4 key购买 nike

我正在尝试找出对 Pandas 数据框执行搜索和排序的最快方法。以下是我要完成的数据帧之前和之后的数据帧。

之前:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
ABC DEF 123 456 8000 8000
DEF XYZ 456 893 9999 9999
AAA BBB 473 917 5555 5555
BBB CCC 917 341 5555 5555

搜索/排序后:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
ABC XYZ 123 893 8000 9999
AAA CCC 473 341 5555 5555

在这个例子中,我实际上是在尝试过滤掉存在于终点目的地之间的“航类”。这应该通过使用某种删除重复方法来完成,但让我感到困惑的是如何处理所有列。二进制搜索是完成此操作的最佳方法吗?感谢提示,努力解决这个问题。

可能的边缘情况:

如果数据被切换并且我们的端连接在同一列怎么办?

flight1  flight2      1Num    2Num     1Code   2Code
ABC DEF 123 456 8000 8000
XYZ DEF 893 456 9999 9999

搜索/排序后:

flight1  flight2      1Num    2Num     1Code   2Code
ABC XYZ 123 893 8000 9999

这种情况在逻辑上不应该发生。毕竟你怎么能去 DEF-ABC 和 DEF-XYZ?你不能,但“端点”仍然是 ABC-XYZ

最佳答案

这是网络问题,所以我们使用 networkx,注意,这里你可以有两个以上的停靠站,这意味着你可以遇到像 NY-DC-WA-NC

import networkx as nx
G=nx.from_pandas_edgelist(df, 'flightTo', 'flightFrom')

# create the nx object from pandas dataframe

l=list(nx.connected_components(G))

# then we get the list of components which as tied to each other ,
# in a net work graph , they are linked
L=[dict.fromkeys(y,x) for x, y in enumerate(l)]

# then from the above we can create our map dict ,
# since every components connected to each other ,
# then we just need to pick of of them as key , then map with others

d={k: v for d in L for k, v in d.items()}

# create the dict for groupby , since we need _from as first item and _to as last item
grouppd=dict(zip(df.columns.tolist(),['first','last']*3))
df.groupby(df.flightTo.map(d)).agg(grouppd) # then using agg with dict yield your output

Out[22]:
flightTo flightFrom toNum fromNum toCode fromCode
flightTo
0 ABC XYZ 123 893 8000 9999
1 AAA CCC 473 341 5555 5555

安装networkx

  • Pip:pip install networkx
  • Anaconda:conda install -c anaconda networkx

关于python - 对 Pandas 数据框执行复杂搜索的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com