Remap values in pandas column with a dict

后端 未结 10 1100
囚心锁ツ
囚心锁ツ 2020-11-21 05:14

I have a dictionary which looks like this: di = {1: \"A\", 2: \"B\"}

I would like to apply it to the \"col1\" column of a dataframe similar to:

10条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:51

    A more native pandas approach is to apply a replace function as below:

    def multiple_replace(dict, text):
      # 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) 
    

    Once you defined the function, you can apply it to your dataframe.

    di = {1: "A", 2: "B"}
    df['col1'] = df.apply(lambda row: multiple_replace(di, row['col1']), axis=1)
    

提交回复
热议问题