pandas 返回数据帧中不在其他数据帧中的列 [英] pandas return columns in dataframe that are not in other dataframe
问题描述
我有两个如下所示的数据框:
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 函数,我可以做这样的事情
<预><代码>>>>打印 df_2.columns.isin(df_1.columns)数组([真,真,假],dtype=bool)列B
和C
来自df_2
存在于df_1
而D
不存在没有
我的问题是:有没有人知道一种方法来返回存在于 df_2 但不存在于 df_1 的列的列标签
类似的东西
array([u'D'], dtype=string)
先谢谢你!
Pandas 索引对象具有类似集合的属性,因此您可以直接执行:
df_2.columns.difference(df_1.columns)索引([u'D'],dtype='object')
您还可以使用 &|^
等运算符来计算交集、并集和对称差:
df_1.columns &df_2.columns索引([u'B', u'C'], dtype='object')df_1.columns |df_2.columns索引([u'A', u'B', u'C', u'D'], dtype='object')df_1.columns ^ df_2.columns索引([u'A', u'D'], dtype='object')
曾经有 -
运算符用于差异,现在已弃用:
df_2.columns - df_1.columnsFutureWarning:不推荐使用-"来提供与索引的集合差异,请使用 .difference()索引([u'D'],dtype='object')
I have two dataframes that look like this:
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]
})
Now if I utilize pandas .isin function I can do something nifty like this
>>> print df_2.columns.isin(df_1.columns)
array([ True, True, False], dtype=bool)
Columns B
and C
from df_2
exist in df_1
while D
doesn't
My question is: does anyone know of a way to return the columns' labels for columns that exist in df_2 but not in df_1
something like this
array([u'D'], dtype=string)
Thank you in advance!
Pandas index object have set-like properties, so you can directly do:
df_2.columns.difference(df_1.columns)
Index([u'D'], dtype='object')
You can also use operators like &|^
to compute intersection, union and symmetric difference:
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')
There use to be the -
operator for difference, now deprecated:
df_2.columns - df_1.columns
FutureWarning: using '-' to provide set differences with Indexes is deprecated, use .difference()
Index([u'D'], dtype='object')
这篇关于pandas 返回数据帧中不在其他数据帧中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!