使用Pandas查找两个csv之间的部分字符串匹配,并使用第一个csv的索引输出匹配结果

2024-05-16 09:52:04 发布

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

我想比较两个CSV之间的两列,找到部分字符串匹配,然后在第一个CSV的正确索引处追加匹配行(包括列中的等效项)中的所有数据,然后在第三个CSV中输出编译的匹配项,而不编辑前两个CSV中的任何一个。无论是否找到匹配项,第一个CSV中的所有行都必须显示在第三个CSV上,但仅显示第二个CSV中的匹配行。例如:

CSV_1                               CSV_2
Name     City     Date              Name_of_thing     City_of_Origin     Time
Examp.   Bton     7/11              huh, inc.         Lton, AMERICA  7/10/2020 00:00
Nomatch  Cton     10/10             THE EXAMPLE, LLC  Bton, USA        7/11/2020 00:00

将显示为

CSV_3
Name     City     Date    Name_of_thing     City_of_Origin     Time
Examp.   Bton     7/11    THE EXAMPLE, LLC  Bton, USA          7/11/2020 00:00
Nomatch  Cton     10/10

我之前在这里发布了关于模糊匹配方法(Record linking two large CSVs in Python?)的问题,但是解决方案最终效率非常低,所以我希望一个简单的正则表达式搜索就足够了。这些文件都非常大,长度也不相同,所以我想知道是否有一种解决方案可以让CSV_1中的所有条目与CSV_2中的条目进行有效的比较

不幸的是,项目的限制不允许我将CSV加载到数据库中,这将使这更容易,因此我需要完全依靠Pandas来完成这项工作

谢谢


Tags: ofcsvthenamecitydatetimeexample
1条回答
网友
1楼 · 发布于 2024-05-16 09:52:04

只需做一点腿部工作,使日期和城市保持一致。然后是一个简单的左merge()

import pandas as pd
import io
import datetime as dt

CSV_1 = pd.read_csv(io.StringIO(                              
"""Name     City     Date              
Examp.   Bton     7/11              
Nomatch  Cton     10/10"""), sep="\s\s+", engine="python")             
    
CSV_2 = pd.read_csv(io.StringIO(
"""Name_of_thing     City_of_Origin     Time
huh, inc.         Lton, AMERICA  7/10/2020 00:00
THE EXAMPLE, LLC  Bton, USA        7/11/2020 00:00"""), sep="\s\s+", engine="python") 

# need to make dates consistent and joinable
# need to pull city out of City_of_origin
CSV_3 = CSV_1.assign(
    datekey=pd.to_datetime(CSV_1["Date"]+f"/{dt.date.today().year}")
).merge(
    CSV_2.assign(
        datekey=pd.to_datetime(CSV_2["Time"]),
        City=lambda dfa: dfa["City_of_Origin"].str.extract("([A-Za-z]*)")
    ),
    on=["datekey","City"],
    how="left"
).drop(columns="datekey")

print(CSV_3.to_string())

输出

      Name  City   Date     Name_of_thing City_of_Origin             Time
0   Examp.  Bton   7/11  THE EXAMPLE, LLC      Bton, USA  7/11/2020 00:00
1  Nomatch  Cton  10/10               NaN            NaN              NaN

相关问题 更多 >