Remap values in pandas column with a dict

后端 未结 10 1073
囚心锁ツ
囚心锁ツ 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:47

    Adding to this question if you ever have more than one columns to remap in a data dataframe:

    def remap(data,dict_labels):
        """
        This function take in a dictionnary of labels : dict_labels 
        and replace the values (previously labelencode) into the string.
    
        ex: dict_labels = {{'col1':{1:'A',2:'B'}}
    
        """
        for field,values in dict_labels.items():
            print("I am remapping %s"%field)
            data.replace({field:values},inplace=True)
        print("DONE")
    
        return data
    

    Hope it can be useful to someone.

    Cheers

提交回复
热议问题