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

2024-04-25 05:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一张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']

我不赞成使用pandas和dataframes,我只是认为这是处理excel数据的最佳方式。你知道吗

如果有人能在任何方面提供帮助,我们将不胜感激!你知道吗

干杯


Tags: 数据keyimport版本pandasdf差异excel
2条回答

您可以尝试以下公式:

=IF(FIND(A2,B2)>1,LEFT(B2,FIND(A2,B2)-1),IF(FIND(B2,B2)=1,RIGHT(B2,LEN(B2)-LEN(A2))))

可以将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

replace一起使用.apply

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

相关问题 更多 >