Remap values in pandas column with a dict

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

    Or do apply:

    df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
    

    Demo:

    >>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
    >>> df
      col1 col2
    0    w    a
    1    1    2
    2    2  NaN
    >>> 
    

提交回复
热议问题