Skip to main content
 首页 » 编程设计

python之Pandas 返回数据框中不在其他数据框中的列

2025年05月04日1698°冷暖

我有两个如下所示的数据框:

df_1 = pd.DataFrame({ 
'A' : [1.0, 2.0, 3.0, 4.0], 
'B' : [100, 200, 300, 400], 
'C' : [2, 3, 4, 5]  
                   }) 
 
df_2 = pd.DataFrame({ 
'B' : [1.0, 2.0, 3.0, 4.0], 
'C' : [100, 200, 300, 400], 
'D' : [2, 3, 4, 5]  
                  }) 

现在,如果我使用 pandas .isin 函数,我可以做一些像这样漂亮的事情

>>> print df_2.columns.isin(df_1.columns) 
array([ True,  True, False], dtype=bool) 

df_2 中的 B 和 C 存在于 df_1 中,而 D 不存在't

我的问题是:有没有人知道返回 df_2 中存在但 df_1 中不存在的列的列标签的方法

像这样

array([u'D'], dtype=string) 

提前致谢!

请您参考如下方法:

Pandas index object具有类似集合的属性,因此您可以直接执行以下操作:

df_2.columns.difference(df_1.columns) 
Index([u'D'], dtype='object') 

您还可以使用 &|^ 等运算符来计算交集、并集和对称差:

df_1.columns & df_2.columns 
Index([u'B', u'C'], dtype='object') 
 
df_1.columns | df_2.columns 
Index([u'A', u'B', u'C', u'D'], dtype='object') 
 
df_1.columns ^ df_2.columns 
Index([u'A', u'D'], dtype='object') 

曾经有 - 运算符来表示差异,现在已弃用:

df_2.columns - df_1.columns 
FutureWarning: using '-' to provide set differences with Indexes is deprecated, use .difference() 
Index([u'D'], dtype='object')