我有一本我们的系统(出于某种原因)适用于数据的一些城市名称的缩写字典(即“堪萨斯城”缩写为“堪萨斯 CY”,俄克拉荷马城拼写正确)。
我在让我的函数应用于数据框的列时遇到问题,但是当我传入数据字符串时它可以工作。下面的代码示例:
def multiple_replace(text, dict):
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
testDict = {"Kansas CY": "Kansas City"}
dfData['PREV_CITY'] = dfData['PREV_CITY'].apply(multiple_replace, dict=testDict)
当我在最后一行添加'axis = 1'时,它会出错,说我提供了太多的参数。否则,它运行时不会出错,它只是在与字典匹配时不进行更改。
先感谢您!-里斯