Removing labels in a dataset based on values from a column in a different dataset

Viewed 47

I have the df shown below where data is used for an exercise on virus spreading.

df1

Node       Target    Node_Label    Target_Label
A            B           1               0
B            A           0               1
C            A           1               1
C            D           1               1
 

I need to remove the labels of Node/Target based on the column Selected in the df below:

Node   Label    Selected 
A         1        True
B         0        False
C         1        True
D         1        False
E         0        False
F         1        False
G         -1       True

The expected output therefore would be

Node       Target    Node_Label    Target_Label
A            B                          0
B            A           0              
C            A                         
C            D                          1

How can I remove the labels in df1 based on the Selected values in df2? Would a filter condition where I check the condition of Selected in df2 and apply it in df1 good in this case?

1 Answers

You could try this:

import pandas as pd

df1 = pd.DataFrame(
    {
        "Node": {0: "A", 1: "B", 2: "C", 3: "C"},
        "Target": {0: "B", 1: "A", 2: "A", 3: "D"},
        "Node_Label": {0: 1, 1: 0, 2: 1, 3: 1},
        "Target_Label": {0: 0, 1: 1, 2: 1, 3: 1},
    }
)

df2 = pd.DataFrame(
    {
        "Node": {0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", 6: "G"},
        "Label": {0: 1, 1: 0, 2: 1, 3: 1, 4: 0, 5: 1, 6: -1},
        "Selected": {
            0: "True",
            1: "False",
            2: "True",
            3: "False",
            4: "False",
            5: "False",
            6: "True",
        },
    }
)

mask = df2.loc[df2["Selected"] == "True", "Node"].to_list()  # ['A', 'C', 'G']

df1.loc[df1["Node"].isin(mask), "Node_Label"] = ""
df1.loc[df1["Target"].isin(mask), "Target_Label"] = ""

print(df1)
# Output
  Node Target Node_Label Target_Label
0    A      B                       0
1    B      A          0
2    C      A
3    C      D                       1
Related