Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

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 :-/

2 Answers

0 votes
by (41.4k points)

You can use .replace.

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

0 votes
by (106k points)

You can use the below-mentioned code to remap values in pandas column with a dict:-

def remap(data,dict_labels): 

for field,values in dict_labels.items():

print("I am remapping %s"%field) data.replace({field:values},inplace=True) 

print("DONE") 

return data

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...