Map/Replace values from one column with lookup to values from another column

Question:

Three dataframes. In DataFrame1, how to replace the values from columns From_ and To_ with the corresponding values in column Name in DataFrame2 (for To_) and DataFrame3 (for From_)? Note that values for From_ and To_ in DataFrame1 are index references that start at 1 and not 0. So value 2 in To_ should reference Name2 in DataFrame2. Thank you very much for your help.

DataFrame1:

    S    From_   To_
0   x    NaN     None
1   x    NaN     None
2   x    NaN     None
3   x    1.0     2
4   x    1.0     5
5   x    NaN     None
6   x    NaN     None
7   x    NaN     None
8   x    NaN     None
9   x    NaN     None
10  x    1.0     NaN

DataFrame2:

     A   Name
0  None  Name1
1  None  Name2
2  None  Name3
3  None  Name4
4  None  Name5

DataFrame3:

     A   Name
0  None  Name6
1  None  Name7
2  None  Name9
3  None  Name10

How to change DataFrame1 to look like this:

    S    From_     To_
0   x    NaN       None
1   x    NaN       None
2   x    NaN       None
3   x    Name6     Name2
4   x    Name6     Name5
5   x    NaN       None
6   x    NaN       None
7   x    NaN       None
8   x    NaN       None
9   x    NaN       None
10  x    Name6     NaN
Asked By: Rycliff

||

Answers:

You can simply do a map

df1['From_'] = pd.to_numeric(df1['From_'], errors='coerce').sub(1).map(df3['Name'])
df1['To_']   = pd.to_numeric(df1['To_'], errors='coerce').sub(1).map(df2['Name'])
    S  From_    To_
0   x    NaN    NaN
1   x    NaN    NaN
2   x    NaN    NaN
3   x  Name6  Name2
4   x  Name6  Name5
5   x    NaN    NaN
6   x    NaN    NaN
7   x    NaN    NaN
8   x    NaN    NaN
9   x    NaN    NaN
10  x  Name6    NaN
Answered By: Ynjxsjmh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.