Python 选择数据帧之间的补足列

Python 选择数据帧之间的补足列,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有一个pandas.DataFramex,x被馈送到函数filter,并返回y,一个从x删除了一些列的数据框。函数是一个黑盒,列数很大。如何在“x”中找到已删除的列 或者,y.columns是x.columns的子集,如何在x中找到不在y中的列 例如: x = pd.DataFrame(np.array([[1,2,3],[4,5,6]])) x.columns = list('abc') y = x.iloc[:, :2].copy() >>> x a b c

假设我有一个pandas.DataFrame
x
x
被馈送到函数
filter
,并返回
y
,一个从
x
删除了一些列的数据框。函数是一个黑盒,列数很大。如何在“x”中找到已删除的列

或者,
y.columns
x.columns
的子集,如何在
x
中找到不在
y
中的列

例如:

x = pd.DataFrame(np.array([[1,2,3],[4,5,6]]))
x.columns = list('abc')
y = x.iloc[:, :2].copy()
>>> x
   a  b  c
0  1  2  3
1  4  5  6
>>> y
   a  b
0  1  2
1  4  5
我希望返回列
c

我现在的解决方案是:

>>> xc = x.columns.values.tolist()
>>> yc = y.columns.values.tolist()
>>> diff = [i for i in xc if i not in yc]
>>> x[diff]
   c
0  3
1  6
有没有一种方法可以在不提取列名的情况下获得结果

我以为这是一些基本的操作,但我在网上找不到一个简单的答案

谢谢。

将熊猫用作:

或:

这将给出
x
dataframe中的列值,但不在
y
dataframe中


或:

使用
集合

x_col = set(x.columns)
y_col = set(y.columns)
x_col.difference(y_col)
>>{'c'}

x\u col.difference(y\u col)
将返回仅存在于
x\u col
中而不存在于
y\u col
中的元素。您可以使用
numpy
来实现以下目的:

import numpy as np

diff = np.setdiff1d(xc,yc)

但是,使用本机方法总是好的:

diff = list(xc - yc)
print(x[list(set(x.columns)-set(y.columns))])

   c
0  3
1  6
x_col = set(x.columns)
y_col = set(y.columns)
x_col.difference(y_col)
>>{'c'}
import numpy as np

diff = np.setdiff1d(xc,yc)
diff = list(xc - yc)