Remap values in pandas column with a dict, preserve NaNs

ghz 1years ago ⋅ 10234 views

Question

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:

     col1   col2
0       w      a
1       1      2
2       2    NaN

to get:

     col1   col2
0       w      a
1       A      2
2       B    NaN

How can I best do this?


Answer

You can use [.replace](https://pandas.pydata.org/pandas- docs/stable/generated/pandas.DataFrame.replace.html). For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the [Series](https://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.replace.html), i.e. df["col1"].replace(di, inplace=True).