python-根据与另一个列表匹配的值在数据框中删除行

时间:2020-07-23 17:47:32

标签: python pandas

在我的数据帧(df)中,对于每一行,我都需要删除几行,它们的node1和node2列中的值都与另一个列表(组)匹配。

df = pd.DataFrame(dict(node1=["A","A","B","C","D"], node2=["B","D","E","F","G"]))
> df
    node1   node2
0   A   B
1   A   D
2   B   E
3   C   F
4   D   G

groups = ["A","B","C","F"]
> groups
['A', 'B', 'C', 'F']

在此示例中,df的第0行和第3行的值均与我的网上论坛列表匹配,因此我需要删除这些行。 我的新数据框将是:

df2 = pd.DataFrame(dict(node1=["A","B","D"], node2=["D","E","G"]))
> df2
    node1   node2
0   A   D
1   B   E
2   D   G

2 个答案:

答案 0 :(得分:1)

尝试使用.isin().all(1)

df.loc[~df.isin(groups).all(1)]
#output:
    node1   node2
1   A       D
2   B       E
4   D       G

答案 1 :(得分:0)

   import pandas as pd 
   df = pd.DataFrame(dict(node1=["A","A","B","C","D"], node2=["B","D","E","F","G"]), columns=["node1", "node2"])
   groups = ["A","B","C","F"]

   df = df.loc[~((df["node1"].isin(groups)) & (df["node2"].isin(groups)))]