Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remap values in pandas column with a dict, preserve NaNs

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? For some reason googling terms relating to this only shows me links about how to make columns from dicts and vice-versa :-/

like image 506
TheChymera Avatar asked Nov 27 '13 18:11

TheChymera


People also ask

How do you remap values in pandas DataFrame column with a dictionary and preserve NANS?

use df. replace({"Duration": dict_duration},inplace=True) to remap none or NaN values in pandas DataFrame with Dictionary values. To remap None / NaN values of the 'Duration ' column by their respective codes using the df. replace() function.

Can a dictionary hold a DataFrame?

A pandas DataFrame can be converted into a Python dictionary using the DataFrame instance method to_dict(). The output can be specified of various orientations using the parameter orient. In dictionary orientation, for each column of the DataFrame the column value is listed against the row label in a dictionary.


1 Answers

You can use .replace. 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, i.e. df["col1"].replace(di, inplace=True).

like image 134
DSM Avatar answered Sep 29 '22 10:09

DSM