![](/img/trans.png)
[英]How to check if all the elements in list are present in pandas column
[英]Pandas - check to see if all elements in a list are in a column
我有一個包含3列的數據框-'sport''age''name'
我有一個包含不同運動項目的列表,聲明如下:
sports = ['tennis','cricket','swimming']
我想檢查一下是否所有3種運動都在運動欄中。 目前,我有這個:
if (df['sport']!=sport).any():
print('no, the sports arent in the column')
因此,如果列表中的所有運動不在該列中,我要打印否。 我當前代碼的問題是,運動列中的元素比運動列表中的元素多得多,因此給我一個錯誤。
嘗試使用isin(sports).all()
例如:
import pandas as pd
sports = ['tennis','cricket','swimming']
df = pd.DataFrame({'sport': ['tennis','cricket','swimming']})
print(df["sport"].isin(sports).all())
您可以使用set.intersection
:
if not set(df['sport']).intersection(set(sports)):
print('no, the sports arent in the column')
更有效地,您可以使用set.issubset
:
if not set(sports).issubset(set(df['sport'])):
print('no, the sports arent in the column')
我相信需要比較set
:
sports = ['tennis','cricket','swimming']
df = pd.DataFrame({'sport': ['tennis','cricket']})
print (df)
sport
0 tennis
1 cricket
print(set(df['sport']) >= set(sports))
False
df = pd.DataFrame({'sport': ['tennis','cricket','swimming']})
print (df)
sport
0 tennis
1 cricket
2 swimming
print(set(df['sport']) >= set(sports))
True
df = pd.DataFrame({'sport': ['tennis','cricket','swimming', 'another']})
print (df)
sport
0 tennis
1 cricket
2 swimming
3 another
print(set(df['sport']) >= set(sports))
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.