Проверьте, присутствует ли данный столбец в Pandas DataFrame или нет
Рассмотрим Dataframe с 4 столбцами: ConsumerId, CarName, CompanyName и Price. Мы должны определить, присутствует ли конкретный столбец в DataFrame или нет.
В этой программе pandas мы используем атрибут Dataframe.columns, который возвращает метки столбцов данного Dataframe.
Syntax: Dataframe.columns
Parameter: None
Returns: column names
Let’s create a Datafame:
Code:
Python
# import pandas libraryimport pandas as pd # dictionaryd = {"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 dataframedf = pd.DataFrame(d) # show the dataframedf |
Выход:

Example 1: To check whether the ‘ConsumerId’ column exists in Dataframe or not.
Python
if "ConsumerId" in df.columns : print("ConsumerId column is present") else: print("ConsumerId column is not present") |
Выход:
Столбец ConsumerId присутствует
Пример 2: Чтобы проверить, существует ли столбец «CarName» в Dataframe или нет.
Python
if "CarName" in df.columns: print("CarName column is present") else: print("CarName column is not present") |
Выход:
Столбец CarName присутствует
Example 3: To check whether the ‘CarType’ column exists in Dataframe or not.
Python
if "CarType" in df.columns: print("CarType column is present") else: print("CarType column is not present") |
Выход:
Столбец CarType отсутствует
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.