3

Having the following pandas Dataframe sample:

df = pd.DataFrame([[1,2],[1,2],[3,5]])

df
    0   1
0   1   2
1   1   2
2   3   5

And the following dictionary:

d = {1:'foo',2:'bar',3:'tar',4:'tartar',5:'foofoo'}

I would like to "translate" the dataframe by using the dictionary d. The output looks like:

result = pd.DataFrame([['foo','bar'],['foo','bar'],['tar','fofo']])

result
    0   1
0   foo bar
1   foo bar
2   tar fofo

I would like to avoid using for loops. The solution I'm trying to find is something with map or similars...

PeCaDe
  • 277
  • 1
  • 8
  • 33

1 Answers1

8

Solution

  • Replacing whole dataframe:

    result_1 = df.replace(d)
    
  • Replacing a specific column of a dataframe:

    result_2 = df.replace({"COLUMN":d})
    
Felipe Trenk
  • 341
  • 2
  • 8