在pandas中将一个Excel文件与另一个Excel文件进行匹配并获取值

2024-09-28 01:25:23 发布

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

我有两个excel文件,我将它们命名为:源.xlsx输出.xlsx。在

我需要使用Caller ID列匹配数据源.xlsx到svc_列输出.xlsx

如果不匹配,或者使用Caller ID列的值为“NULL”,我可以使用adsl列源.xlsx端口列匹配输出.xlsx。在

如果有匹配项,那么我应该忽略端口并写入呼叫者ID

中的数据源.xlsx如下所示:

Caller ID    adsl    Comparison Result
NULL         2/12    Not Match
11111111     2/267   Match
22222222     4/243   Match
22222222     2/117   Possible Match

中的数据输出.xlsx如下所示:

^{pr2}$

我的预期输出是从写入数据源.xlsx输出.xlsx

svc_no              Caller ID    port    Comparison Result
22222222            22222222     4/243   Match
11111111            11111111     2/267   Match
22222222            22222222     2/117   Possible Match 
NULL                NULL         2/12    Not Match

我尝试使用:

df = read_excel('source.xlsx')
df1 = read_excel('output.xlsx')

df = df['Caller ID'].isin(df1['svc_no'])]
df['Caller ID'] = df1['Caller ID']

df1.to_excel('output.xlsx')

但是它不匹配并且随机写入。在


Tags: 端口iddfmatchnotresultxlsxexcel
1条回答
网友
1楼 · 发布于 2024-09-28 01:25:23

这是一种方法。在

# filter output for 2 pre-populated columns
output = output[['svc_no', 'port']]

# add duplicate column
output['Caller ID'] = output['svc_no']

# create series mapping from source
s = source.set_index(['Caller ID', 'adsl'])['Comparison Result']

# map series to output
output['Comparison Result'] = output.set_index(['svc_no','port']).index.map(s.get)

print(output)

        svc_no   port    Caller ID Comparison Result
0  2.22222e+07  4/243  2.22222e+07             Match
1  1.11111e+07  2/267  1.11111e+07             Match
2  2.22222e+07  2/117  2.22222e+07     PossibleMatch
3         NULL   2/12         NULL          NotMatch

相关问题 更多 >

    热门问题