Simplified dfs:
df = pd.DataFrame(
{
"ID": [6, 2, 4],
"to ignore": ["foo", "whatever", "idk"],
"value": ["A", "B", "A"],
}
)
df2 = pd.DataFrame(
{
"ID_number": [1, 2, 3, 4, 5, 6],
"A": [0.91, 0.42, 0.85, 0.84, 0.81, 0.88],
"B": [0.11, 0.22, 0.45, 0.38, 0.01, 0.18],
}
)
ID to ignore value
0 6 foo A
1 2 whatever B
2 4 idk A
A B ID_number
0 0.91 0.11 1
1 0.42 0.22 2
2 0.85 0.45 3
3 0.84 0.38 4
4 0.81 0.01 5
5 0.88 0.18 6
I want to add a column to df which includes combinations of df['ID'] to df2['ID_number'] and df['value'] to the df2 column matching the value in df[value] (either 'A' or 'B').
We can add a column of matching values where the lookup column name in df2 is given, 'A':
df["NewCol"] = df["ID"].map(
df2.drop_duplicates("ID_number").set_index("ID_number")["A"]
)
Which gives:
ID to ignore value NewCol
0 6 foo A 0.88
1 2 whatever B 0.42
2 4 idk A 0.84
But this doesn't give values for B, so the value '0.42' above when looking for 'B' should instead be '0.22'.
df["NewCol"] = df["ID"].map(
df2.drop_duplicates("ID_number").set_index("ID_number")[df["value"]]
)
obviously doesn't work. How can do I this?