gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:33:27 25 4
gpt4 key购买 nike

我正在尝试使用字典来模糊匹配 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com