查找两个数据帧/列表中的字符串之间的差异,输出差异

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

所以我有一个excel表,我试图分析两个版本之间的差异。具体来说,我有两列; A和B.我导入到python并使用pandas我将A和B都设置为自己的数据帧(分别称为dfA和dfB)。他们在这里有以下内容:

key dfA dfB 1 cat bigcat 2 dog smalldog 3 mouse hugemouse 4 child normalchild

我试图输出第三列包含两个数据帧之间的字符串差异,所以基本上是第三个数据帧/列:

ABdifference
big
small
huge
normal

我已经研究过使用difflib库但是我不认为它会以可读的格式产生结果

我会粘贴到目前为止我所拥有的代码,但它实际上并不多,因为我在一段时间内没有编码,我认为它比我认为的更容易...

import pandas as pd
from pandas import ExcelWriter
import difflib

df = pd.read_excel('somesheet.xlsx', sheet_name='Diff')

first= df['A']
second = df['B']

我与使用熊猫和数据帧的想法没有结合,我只是认为这是获得excel数据的最佳方式。

如果有人可以提供任何帮助,我们将非常感激!

干杯

python excel pandas
2个回答
0
投票

你可以使用Dataframe.applylambda函数:

print(dfA, '\n')
print(dfB)

    col1
0    cat
1    dog
2  mouse
3  child 

          col2
0       bigcat
1     smalldog
2    hugemouse
3  normalchild

将数据框与pd.concat结合使用:

df_combined = pd.concat([dfA, dfB], axis=1)
print(df_combined)
    col1         col2
0    cat       bigcat
1    dog     smalldog
2  mouse    hugemouse
3  child  normalchild

使用.applyreplace

df_combined['col'] = df_combined.apply(lambda x: x['col2'].replace(x['col1'], ''), axis=1)

print(df_combined)
    col1         col2     col
0    cat       bigcat     big
1    dog     smalldog   small
2  mouse    hugemouse    huge
3  child  normalchild  normal

0
投票

您可以尝试以下公式:

=IF(FIND(A2,B2)>1,LEFT(B2,FIND(A2,B2)-1),IF(FIND(B2,B2)=1,RIGHT(B2,LEN(B2)-LEN(A2))))
© www.soinside.com 2019 - 2024. All rights reserved.