I have a datafarme
import pandas as pd
df = pd.DataFrame({"type": ["A" ,"A1" ,"A" ,"A1","B" ],
"group": ["g1", "g2","g2","g2","g1"]})
And i have a dictionary
dic ={"AlphaA": {"A": {"g1":"A_GRP1", "g2":"A_GRP2"},
"A1": {"g1":"A1_GRP1", "g2":"A1_GRP2"}},
"AlphaB": {"B": {"g1":"B_GRP1", "g2":"B_GRP2"}},
}
i have to create a column name "value", which will use the data frame and dictionary and get value assigned to it
Conditions to be applied:
- if type is "A" or "A1" it should refer dictionary key AlphaA and get the value for respective group and assign it to new column
- if type is "B", it should refer dictionary key AlphaB and get the value of the respective group
Example of row one:
type is "A" hence refering dictionary key "AlphaA"
group is "g1
therefore :
dictt["AlphaA"]["A"]["g1"] #would be the answer
Required Output
final_df = pd.DataFrame({"type" : ["A" ,"A1" ,"A" ,"A1","B" ],
"group": ["g1", "g2","g2","g2","g1"],
"value": ["A_GRP1", "A1_GRP2", "A_GRP2",
"A1_GRP2", "B_GRP1"]})
I was able to achieve this using loops but its is taking lot of time,
hence looking for some speedy technique.