我有一个数据场
import pandas as pd
df = pd.DataFrame({"type": ["A" ,"A1" ,"A" ,"A1","B" ],
"group": ["g1", "g2","g2","g2","g1"]})
我有一本字典
dic ={"AlphaA": {"A": {"g1":"A_GRP1", "g2":"A_GRP2"},
"A1": {"g1":"A1_GRP1", "g2":"A1_GRP2"}},
"AlphaB": {"B": {"g1":"B_GRP1", "g2":"B_GRP2"}},
}
我必须创建一个列名"value",它将使用数据框架和字典并为其指定值
Conditions to be applied:
- 如果类型为"A"或"A1",则应参考字典键AlphaA,获取相应组的值,并将其分配给新列
- 如果类型为"B",则应参考字典键AlphaB并获得相应组的值
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.