Python 比较两个数据帧并根据查找表删除列

Python 比较两个数据帧并根据查找表删除列,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有两个数据帧: df1: df2: 我想根据df2(查找表)中的值删除df1中的列。只要df2有1,我就必须删除df1中的该列 所以我的最终输出应该是这样的 A B C F 0 63 9 56 0 1 40 35 69 45 2 51 95 55 34 3 25 11 67 89 4 91 10 43 95 5 2 47 8 9 6 37 10 33 20 7 40 88 6 79 8

我有两个数据帧:

df1:

df2:

我想根据df2(查找表)中的值删除df1中的列。只要df2有1,我就必须删除df1中的该列

所以我的最终输出应该是这样的

    A   B   C   F
0   63  9   56  0
1   40  35  69  45
2   51  95  55  34
3   25  11  67  89
4   91  10  43  95
5   2   47  8   9
6   37  10  33  20
7   40  88  6   79
8   75  87  49  69
9   92  21  86  41
假设
len(df1.columns)==len(df2.columns)


如果列不相同,但
df2
df1
中有一部分列,则

df1.reindex(df2.columns[~df2.loc[0].astype(bool)], axis=1)
或使用
拖放
,类似于@student的方法:

df1.drop(df2.columns[df2.loc[0].astype(bool)], axis=1)


您可以尝试使用
drop
删除列:

remove_col = df2.columns[(df2 == 1).any()] # get columns with any value 1
df1.drop(remove_col, axis=1, inplace=True) # drop the columns in original dataframe
或者,在一行中:

df1.drop(df2.columns[(df2 == 1).any()], axis=1, inplace=True)

列可以进行
交叉

df1[df1.columns.intersection(df2.columns[~df2.iloc[0].astype(bool)])]
Out[354]: 
    A   B   C   F
0  63   9  56   0
1  40  35  69  45
2  51  95  55  34
3  25  11  67  89
4  91  10  43  95
5   2  47   8   9
6  37  10  33  20
7  40  88   6  79
8  75  87  49  69
9  92  21  86  41

以下是易于理解的解决方案:

df1.loc[:,df2.loc[0]!=1]
输出:

    A   B   C   F
0  63   9  56   0
1  40  35  69  45
2  51  95  55  34
3  25  11  67  89
4  91  10  43  95
5   2  47   8   9
6  37  10  33  20
7  40  88   6  79
8  75  87  49  69
9  92  21  86  41

loc
可用于通过布尔或条件查找选择行或列:

您好,谢谢您的帮助,如果列不同怎么办。@BhanuTez请参阅编辑。只要列数相同,这就行了。
df1.drop(df2.columns[(df2 == 1).any()], axis=1, inplace=True)
df1[df1.columns.intersection(df2.columns[~df2.iloc[0].astype(bool)])]
Out[354]: 
    A   B   C   F
0  63   9  56   0
1  40  35  69  45
2  51  95  55  34
3  25  11  67  89
4  91  10  43  95
5   2  47   8   9
6  37  10  33  20
7  40  88   6  79
8  75  87  49  69
9  92  21  86  41
df1.loc[:,df2.loc[0]!=1]
    A   B   C   F
0  63   9  56   0
1  40  35  69  45
2  51  95  55  34
3  25  11  67  89
4  91  10  43  95
5   2  47   8   9
6  37  10  33  20
7  40  88   6  79
8  75  87  49  69
9  92  21  86  41