我有這個資料框
col1 col2 col3
0 a b 1
1 b c 2
2 c d 3
3 d a 4
4 k g 5
5 w x 6
6 y z 7
7 z w 8
8 r w 9
我想要一個輸出,其中我只能在資料框中有一個“回圈”模式
預期輸出:
col1 col2 col3
0 a b 1
1 b c 2
2 c d 3
3 d a 4
5 w x 6
6 y z 7
7 z w 8
我問的可能嗎?
uj5u.com熱心網友回復:
這看起來像一個圖形問題,您可以使用
import networkx as nx
G = nx.from_pandas_edgelist(df, source='col1', target='col2',
create_using=nx.DiGraph)
nodes = {n for l in nx.simple_cycles(G) for n in l}
# {'a', 'b', 'c', 'd', 'w', 'x', 'z'}
out = df.loc[df['col1'].isin(nodes) & df['col2'].isin(nodes)]
# or
# out = df[df[['col1', 'col2']].isin(nodes).all(axis=1)]
print(out)
輸出:
col1 col2 col3
0 a b 1
1 b c 2
2 c d 3
3 d a 4
5 w x 6
6 x z 7
7 z w 8
輸出圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516966.html
標籤:Python熊猫数据框
下一篇:根據唯一條目計算時差
