1

I have two dataframes:

df = pd.DataFrame({'A': [1,2,3,5,4,2], 'B':[1,2,4,1,2,3], 'C':[2,3,1,4,2,3]})
df1 = pd.DataFrame({'num':[1,2,3,4,5],'col':['red','red','blue','orange','orange']})

They look like this:

df:
        A   B   C
    0   1   1   2
    1   2   2   3
    2   3   4   1
    3   5   1   4
    4   4   2   2
    5   2   3   3

df1:

       col    num
   0    red     1
   1    red     2
   2    blue    3
   3    orange  4
   4    orange  5

what i want is the dataframe df with values of df1:

df_new:
        A       B     C
    0   red     red     red
    1   red     red     blue
    2   blue    orange  red
    3   orange  red     orange
    4   orange  red     red
    5   red     blue    blue

Bearing in mind that I have lots of rows in df, and have thousands of different values as well.

Many Thanks!

1 Answer 1

1

if you set the index to the num col on df1 then you can call apply with a lambda and use map to perform the lookup on each column:

In [11]:
df2 = df1.set_index('num')
df.apply(lambda x: x.map(df2['col']))

Out[11]:
        A       B       C
0     red     red     red
1     red     red    blue
2    blue  orange     red
3  orange     red  orange
4  orange     red     red
5     red    blue    blue
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much for quick response, i have been thinking of this for a while! Bless you!
yes, had to wait for a couple of minutes to be able to accept the answer. It's fast enough for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.