python - 迭代 pandas 数据框中的行并匹配列表字典中的值以创建新列

标签 python pandas dataframe

我正在尝试使用字典来模糊匹配 pandas 数据框中的列。我的字典看起来像这样:

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

目标是使用列表别名来匹配我的数据帧列中的字符串,然后生成一个新列,如果发现一个新列,该列将具有客户名称1匹配。我的数据框有 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')

我能够使用少于 100 万行的 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
<小时/>

注意:我们在列表理解中计算了列表 [y for y in dict_ if x in dict_[y] 两次,这是一种耻辱。但这在 python 3.8 中可以使用 walrus operator 来避免。

关于python - 迭代 pandas 数据框中的行并匹配列表字典中的值以创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57112266/

相关文章:

python - 在 Pandas 中获取带有向量的数据帧的点积,并返回数据帧

python - Python 中的 SVD 图像重建

python - 损失函数的爆炸式增长,LSTM 自动编码器

pandas - UnicodeDecodeError : 'utf-8' codec can't decode byte 0xcc in position 3: invalid continuation byte

python - 如何在 pandas 中将值从一个数据帧移动到另一个数据帧?

python - 将 Pandas DataFrame 中的所有行乘以字典

python - pandas.Timedelta 转换为 float 秒太慢

python - 按列分组并获取 Pandas 组的平均值

python - 如何拥有默认对象属性并可以选择设置它?

Python 客户端-服务器脚本挂起,直到我按 [enter]