在两个xlsx文件之间查找相同的行

问题描述 投票:0回答:1

我刚刚看到几个帖子,但我找不到解决方案。

我试图在Python中使用Pandas比较不同工作簿中的2个Excel文件。

WORK1:

A     B     C
1     1     1
2     2     2
3     3     3

WORK2:

A     B     C
1     1     1
2     5     2
3     3     3

欲望输出:

A     B     C
1     1     1

3     3     3

到目前为止,我得到的是:

import pandas as pd

df1 = pd.read_excel('/path/work1.xlsx')
df2 = pd.read_excel('/path/work2.xlsx')

common = df1[df1==df2]
print common
common.to_excel('/path/result.xlsx')

但我得到的是:

A     B     C
1     1     1
2           2
3     3     3

关键是如果work1的列B与work2有任何重合,则输出应该只是整行重合。

我正在使用NGS变体注释,因此分析变体共享的受影响家族将会很有帮助。

python pandas dataframe compare
1个回答
1
投票

您需要做的是编写条件以查找行中相等的所有列。截至目前,您生成的掩码与原始数据帧的形状相同,因此在编制索引时,您可以创建NaN而不是过滤。

选项1 使用eq + all -

df1[df1.eq(df2).all(axis=1)]

   A  B  C
0  1  1  1
2  3  3  3

请记住,在比较时,pandas会通过索引自动对齐数据帧,因此如果您的数据帧与索引或列不相同,则无法使用。如果是这种情况,则需要进行一些预处理。

df2.index = df1.index
df2.columns = df1.columns

现在,这(以及合并)应该工作。


选项2 所有列上的内部merge -

df1.merge(df2)

   A  B  C
0  1  1  1
1  3  3  3
© www.soinside.com 2019 - 2024. All rights reserved.