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

how to conditionally select dataframe rows by comparing column values with a list

I have the following list and dataframe in Python:

import pandas as pd

my_list = ["a", "b", "d"]

d = {'col1': [1, 2, 3, 4], 'col2': ["a", "b", "c", "d"]}
df = pd.DataFrame(data=d)
df

Output:

    col1    col2
0   1       a
1   2       b
2   3       c
3   4       d

But I only want to have such rows in the dataframe where values of col2 also exist in my_list.

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

The final output is supposed to look like the following:

    col1    col2
0   1       a
1   2       b
2   4       d

How can I achieve this without using a for loop?

>Solution :

You can use df.apply for this

df[df['col2'].apply(lambda x: x in my_list)] 
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