深度阅读

How to Check if Column Exists in Pandas

作者
作者
2023年08月22日
更新时间
9.74 分钟
阅读时间
0
阅读量

To check if a column exists in a Pandas DataFrame, you can use the “in” expression with the df.columns attribute. Here’s an example:

import pandas as pd

# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})

# check if 'column1' exists in the DataFrame
if 'column1' in df.columns:
    print('column1 exists')
else:
    print('column1 does not exist')

Output:

column1 exists

You can also check if multiple columns exist by passing a list of column names to the “in” expression. For example:

import pandas as pd

# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})

# check if 'column1' and 'column2' exist in the DataFrame
if all(col in df.columns for col in ['column1', 'column2']):
    print('All columns exist')
else:
    print('At least one column does not exist')

Output:

All columns exist

I hope this helps! Let me know if you have any other questions.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。