1

I have three separate DataFrames:

import pandas as pd

df1 = pd.DataFrame({ "Log": ["1114","1115","1116","1117","1118","1119","120"], "Gender": ["2","2","2","1","1","1","2"] })
df2 = pd.DataFrame({"NAME": ["Gender"],"SOURCE": ["MALE_FEMALE_LIST"]})
df3 = pd.DataFrame({"ID":["0", "1", "2"], "MALE_FEMALE_LIST":["Select", "Male","Female"]})
df3.set_index("ID", inplace = True)

df1 is the location of the data I would like to recode based on information from df3. I would like to say if column header in df1 is the same as the NAME in df2, look in SOURCE in df2 and apply the df3 information to that column.

t.neil89
  • 13
  • 4

1 Answers1

0

Try:

for _, row in df2.iterrows():
    df1[row["NAME"]] = df1[row["NAME"]].map(df3[row["SOURCE"]])

print(df1)

Prints:

    Log  Gender
0  1114  Female
1  1115  Female
2  1116  Female
3  1117    Male
4  1118    Male
5  1119    Male
6   120  Female
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Thanks Andrej. If the problem was slightly more complex, for example (above), where the data is within a nested dict. Would the mapping work? I've edited my question to include an example. – t.neil89 Jul 02 '21 at 12:46
  • https://stackoverflow.com/questions/68287393/python-map-nested-dataframe-dictionary – t.neil89 Jul 07 '21 at 13:54