检查给定列是否存在于 Pandas DataFrame 中
考虑一个包含 4 列的数据框:“ConsumerId”、“CarName”、“CompanyName”和“Price”。我们必须确定 DataFrame 中是否存在特定列。
在这个 pandas 程序中,我们使用Dataframe.columns属性返回给定 Dataframe 的列标签。
Syntax: Dataframe.columns
Parameter: None
Returns: column names
让我们创建一个数据框:
代码:
Python
# 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
Python
if 'ConsumerId' in df.columns :
print('ConsumerId column is present')
else:
print('ConsumerId column is not present')
Python
if 'CarName' in df.columns:
print('CarName column is present')
else:
print('CarName column is not present')
Python
if 'CarType' in df.columns:
print('CarType column is present')
else:
print('CarType column is not present')
输出:
示例 1:检查 Dataframe 中是否存在“ConsumerId”列。
Python
if 'ConsumerId' in df.columns :
print('ConsumerId column is present')
else:
print('ConsumerId column is not present')
输出:
ConsumerId column is present
示例 2:检查 Dataframe 中是否存在“CarName”列。
Python
if 'CarName' in df.columns:
print('CarName column is present')
else:
print('CarName column is not present')
输出:
CarName column is present
示例 3:检查 Dataframe 中是否存在“CarType”列。
Python
if 'CarType' in df.columns:
print('CarType column is present')
else:
print('CarType column is not present')
输出:
CarType column is not present