Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare several dataframe columns to list

I have a Dataframe like this (the columns are not side by side):

 Num A Num B Num C Marked
0  213   314   512
1  612   516   713
2  613   678   125
3  163   813   312

And a list like list = [612,813,512,713]

I now want to compare, if a value from the list is present in the dataframe, and mark it with 1, else with 0, so that the output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 Num A Num B Num C Marked
0  213   314   512      1
1  612   516   713      1
2  613   678   125      0
3  163   813   312      1

I only found out how to do this with a single column:

import pandas as pd
import numpy as np

path = "path"
wb = pd.ExcelFile(path)
df = wb.parse("Sheet1")

list = [612,813,512,713]

df['Marked'] = df.Num_A.isin.(list).astype(int) 


How can you make this to consider all columns?

Thanks in Advance!

>Solution :

You can use np.isin method to check if numbers in lst exist in df along columns and then convert it to integer value:

df['Marked'] = np.isin(df.values,lst).any(axis=1).astype(int)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading