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

Python – How to check if all values in list are in a dataframe column?

I have a dataframe:

data = {'X':['X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E'],
        'Year':[2015, 2016, 2017, 2018, 2015, 2019, 2020, 2021]}
 
df = pd.DataFrame(data)

And a list:

l = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]

I want to check if ALL the values in l appear in data['Year'].

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

E.g. it should return False, as 2022 does not appear in data['Year']

Every example I have found only looks for one value, which I would have to loop through e.g.

2022 in data["Year"].values

Is there a simplier (faster) way of doing this?

Many thanks in advance.

>Solution :

IIUC, you could use set.issubset:

out = set(l).issubset(df['Year'])

Alternatively, you could use all:

out = all(y in df['Year'] for y in l)

Output:

False
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