检查列标题是否与PYTHON匹配

检查列标题是否与PYTHON匹配,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个数据帧: "The column 'Low' is not selected in df2. The column 'Volume' is not selected in df1' df1: df2 我想编写一个函数来检查列标题是否与df1中的列匹配/相同 如果没有,我们会收到一条消息,告诉我们缺少哪个列 给定这些数据帧的消息示例: "The column 'Low' is not selected in df2. The column 'Volume'

我有两个数据帧:

  "The column 'Low' is not selected in df2. The column 'Volume' is not selected in df1' 
df1:

df2

我想编写一个函数来检查列标题是否与df1中的列匹配/相同

如果没有,我们会收到一条消息,告诉我们缺少哪个列

给定这些数据帧的消息示例:

  "The column 'Low' is not selected in df2. The column 'Volume' is not selected in df1' 
我想要一个通用的代码,可以为任何给定的数据帧工作


在python上可以这样做吗?

您可以通过
.columns
访问列名,然后使用set操作检查所需内容:

将熊猫作为pd导入
df1=pd.DataFrame(
{
“ID”:[1],
“打开”:[64],
“高”:[66],
“低”:[52]
}
)
df2=pd.DataFrame(
{
“ID”:[1],
“打开”:[33],
“高”:[45],
“卷”:[30043]
}
)
df1_columns=set(df1.columns)
df2_columns=set(df2.columns)
公共_列=df1_列和df2_列
df1_columns_only=df1_columns-common_columns
df2_columns_only=df2_columns-common_columns
打印(“列仅在df1中可用”,df1\u列仅适用)
打印(“列仅在df2中可用”,df2_列仅适用)
它给出了预期的输出:

Columns only available in df1 {'Low'}
Columns only available in df2 {'Volume'}
df1.columns.difference(df2.columns)
将为您提供df1中不在df2中的collumn
Columns only available in df1 {'Low'}
Columns only available in df2 {'Volume'}