Use another df to replace column values

Viewed 40

Hello I have two df such as

df1

Ancient New 
Seq1.1  Seq1.1_A
Seq2    Se2.4_3

and another

df2

COL1 COL2
A    Seq1.1
B    Plants
C    YP_OODDD
D    Seq2

and I would like to replace COL2 values corresponding to the df.Ancient column and replace it by their corresponding df1.New

and get

COL1 COL2
A    Seq1.1_A
B    Plants
C    YP_OODDD
D    Se2.4_3
2 Answers

Use Series.replace with Series created by DataFrame.set_index and selecting volumn New:

df2['COL2'] = df2['COL2'].replace(df1.set_index('Ancient')['New'])
print (df2)
  COL1      COL2
0    A  Seq1.1_A
1    B    Plants
2    C  YP_OODDD
3    D   Se2.4_3

set the index of 1st dataframe to ancient df.set_index and then use df2.col2.replace(df.new) pass series as an argument.

    df=pd.DataFrame({"col1":["john","amber"],"col2":["a","h"]})
    df2=pd.DataFrame({"ab":["m","g"],"ful":["abraham","heard"]})
    print(df,"\n",df2)
    df2.set_index("ab",inplace=True)
    df.col2=df.col2.replace(df2['ful'])
    df

output:

        col1 col2
    0   john    a
    1  amber    h 

       ab      ful
    0  a  abraham
    1  h    heard

        col1    col2
    0   john    abraham
    1   amber   heard
Related