检查一个给定的列是否存在于Pandas数据框架中
考虑一个有4列的数据框架:’ConsumerId’, ‘CarName’, CompanyName, 和’Price’。我们必须使用Python来确定Pandas Dataframe中的某一列是否存在于数据框架中。
创建一个Dataframe来检查Dataframe中是否存在一个列
# import pandas library
import pandas as pd
# dictionary
d = {'ConsumerId': [1, 2, 3,
4, 5],
'CarName': ['I3', 'S4', 'J3',
'Mini', 'Beetle'],
'CompanyName': ['BMW','Mercedes', 'Jeep',
'MiniCooper', 'Volkswagen'],
'Price': [1200, 1400, 1500,
1650, 1750]
}
# create a dataframe
df = pd.DataFrame(d)
# show the dataframe
df
输出:
使用in关键字检查列是否存在于Pandas中
使用Python关键字检查数据框架中的 “ConsumerId “列是否存在。
if 'ConsumerId' in df.columns :
print('ConsumerId column is present')
else:
print('ConsumerId column is not present')
输出:
ConsumerId column is present
使用issubset()检查列是否存在于Pandas中
使用issubset()函数检查数据框架中是否存在’CarName’和’Price’列。
# Syntax
# {'ColumnName'}.issubset(df.columns)
{'Price', 'CarName'}.issubset(df.columns)
输出:
True
使用all()函数检查列是否存在于Pandas中
使用all()函数检查’Fuel’列是否存在于数据框架中。
all(item in df.columns for item in ['Fuel'])
输出:
False