1

我有一本我们的系统(出于某种原因)适用于数据的一些城市名称的缩写字典(即“堪萨斯城”缩写为“堪萨斯 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'时,它会出错,说我提供了太多的参数。否则,它运行时不会出错,它只是在与字典匹配时不进行更改。

先感谢您!-里斯

4

1 回答 1

2

您可以使用map并传递一个 dict 来用 dict 值替换与 dict 键的完全匹配,因为您可能有区分大小写的匹配,我lower在匹配之前首先将所有字符串:

dfData['PREV_CITY'] = dfData['PREV_CITY'].str.lower().map(testDict, na_action='ignore')

这假设您的 dict 中的键也是小写的

于 2016-09-20T20:07:37.473 回答