性能:用 Python 中字典中的键替换系列值

Performance: Replacing Series values with keys from a Dictionary in Python

我有一个数据系列,其中包含相同组织的各种名称。我想使用映射字典将这些名称协调到给定的标准中。我目前正在使用嵌套的 for 循环遍历每个系列元素,如果它在字典的值内,我将使用字典键更新系列值。

# For example, corporation_series is:
0 'Corp1'
1 'Corp-1'
2 'Corp 1'
3 'Corp2'
4 'Corp--2'
dtype: object

# Dictionary is:
mapping_dict = { 
    'Corporation_1': ['Corp1', 'Corp-1', 'Corp 1'],
    'Corporation_2': ['Corp2', 'Corp--2'],
}

# I use this logic to replace the values in the series
for index, value in corporation_series.items():
    for key, list in mapping_dict.items():
        if value in list:
            corporation_series = corporation_series.replace(value, key)

因此,如果该系列的值为 'Corp1',并且它存在于字典的值中,则逻辑将其替换为公司的相应键。然而,这是一种极其昂贵的方法。有人可以推荐我做这个手术的更好方法吗?非常感谢。

我使用 python 的 .map 函数找到了解决方案。为了使用 .map,我不得不反转我的字典:

# Inverted Dict:
mapping_dict = { 
    'Corp1': ['Corporation_1'],
    'Corp-1': ['Corporation_1'],
    'Corp 1': ['Corporation_1'],
    'Corp2': ['Corporation_2'],
    'Corp--2':['Corporation_2'],
}

# use .map
corporation_series.map(newdict)

而不是 5 分钟的处理,花了大约 5 秒。虽然这是可行的,但我相信还有更好的解决方案。欢迎提出任何建议。