Python 遍历dataframe中的行并匹配列表字典中的值以创建新列

Python 遍历dataframe中的行并匹配列表字典中的值以创建新列,python,pandas,dataframe,Python,Pandas,Dataframe,我正在尝试使用字典来模糊匹配数据帧中的列。我的字典是这样的: { "customer name 1": { "aliases": [ "custname1", "customer name 1", "name 1", ] }, ... } 我们的目标是使用列表别名来匹配我的数据框的一列中的字符串,然后生成一个新列,如果找到匹配项,该列将具有客户名称1。我的dat

我正在尝试使用字典来模糊匹配数据帧中的列。我的字典是这样的:

{
      "customer name 1": {
         "aliases": [
            "custname1",
            "customer name 1",
            "name 1",
         ]
      },
...
}

我们的目标是使用列表
别名
来匹配我的数据框的一列中的字符串,然后生成一个新列,如果找到匹配项,该列将具有
客户名称1
。我的dataframe有26列,但我使用的唯一一列是名为
Business Name
的列。不幸的是,我需要读取中的所有列,因为我需要在最后将它们输出到一个新的csv文件中

我已经生成了一个解决方案,它只处理一小部分数据,但我发现对于一大部分数据,它所花费的时间比我希望的要长得多。目前我正在运行的是:

def create_aggregate_names(workbook: str, names: dict, sheet: str) -> None:
    if '.xlsx' in workbook:
        wb = pd.read_excel(workbook, sheet_name=sheet)
    else:
        chunks = pd.read_csv(workbook, sep='|', encoding='latin-1', warn_bad_lines=True, error_bad_lines=False,chunksize=1000000)
    path = Path(workbook).parents[0]
    # Parse through rows to create an aggregate business name
    for chunk in chunks:
        if "Aggregate Business Name" not in chunk.columns:
            chunk["Aggregate Business Name"] = ""
        for index, row in chunk.iterrows():
            aggregate_name = str(row["Business Name"])
            for name in names:
                if any(alias in str(row["Business Name"]).lower() for alias in names[name]["aliases"]):
                    aggregate_name = name
            chunk.at[index, 'Aggregate Business Name'] = str(aggregate_name)
        chunk.to_csv("{}/data.csv".format(path), sep='|', index=False, mode='a')

我能够用少于一百万行的csv文件很好地运行它。一旦我得到超过100万行,脚本似乎永远运行,没有输出。有没有办法在大数据集上实现这一点?

首先,您可以通过删除级别别名来简化词典:

dict_ = {
      "customer name 1": 
          [
            "custname1",
            "customer name 1",
            "name 1",
         ],
    "customer name 2": ['custom name 2']

      }
然后,我们可以使用双列表理解来加快计算速度:

df = pd.DataFrame({'customer_name' : ['custname1', 'custome name 2', "name 1"]})

df['real_name'] = [ [y for y in dict_ if x in dict_[y]][0] 
                     if len([y for y in dict_ if x in dict_[y]])>0 else ''             
                     for x in df['customer_name'] ]
输出:

    customer_name        real_name
0       custname1  customer name 1
1  custom  name 2  customer name 2
2          name 1  customer name 1


注:如果x在dict_uuy[y]中,则我们计算dict_uuy中y的列表
[y]
在列表中理解了两次,这很遗憾。但是在python 3.8中,使用

可以避免这一点。很高兴我能提供帮助!如果这个答案解决了您的问题,请不要忘记通过单击答案旁边的绿色勾号来接受它。这有助于将注意力集中在未回答的问题上