'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'].
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 1:[1]
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
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | artemis |
