I would like to compare 2 columns of a dataframe values with possibilities that are in a list.
I have this list :
lst=[[1, 1], [2, 1], [4, 1], [6, 2]] #[Poteau,depart]
and this dataframe :
data = {'poteau': [2, 6, 3, 4], 'depart': [1, 2, 3, 1]}
df = pd.DataFrame(data)
I'm expecting this kind of result :
I tried with df.isin() but it does not work as expected. Does somebody have an idea ? Thanks !
CodePudding user response:
You could merge
with indicator
and then filter:
merged = df.merge(pd.DataFrame(lst, columns=df.columns),how="left",indicator="Exist")
output = merged["Exist"].eq("both")
>>> output
0 True
1 False
2 False
3 True
Name: Exist, dtype: bool
CodePudding user response:
Not sure of the logic, you if you want to use isin
and check whether either poteau or depart matches:
pot, dep = zip(*lst)
df['poteau'].isin(pot) | df['depart'].isin(dep)
output:
0 True
1 True
2 False
3 True
dtype: bool