numpy 如何从另一个 Dataframe 重命名行中的值及其标签

42fyovps  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(130)

我有两个 Dataframe ,df1有编码数据,df2有代码及其标签,我想用df1中的标签替换代码。

df1 - 
VBC  VDV
1     5
1     7
2     9
2    10

df2 - 
QCcode    Response     Label
VBC           1         Male
VBC           2        Female
VDV           5        Advertising
VDV           9        Marketing

我试图得到类似于下面的输出:

df_op - 

VBC    VDV
Male    Advertising
Male    Advertising
Female  Marketing
bgtovc5b

bgtovc5b1#

试试这些代码

df1 = pd.DataFrame(data={
    "VBC":[1,1,2,2],
    "VDV":[5,7,9,10]
    })

df2 = pd.DataFrame(data={
    "QCcode":["VBC","VBC","VDV","VDV"],
    "Response":[1,2,5,9],
    "Label":["Male","Female","Advertising","Marketing"]
    })

df2_dict = df2.set_index(list(df2.columns[:2])).to_dict()

con = pd.DataFrame()
for c,part in df1.items():
    part = part.apply(lambda x: df2_dict["Label"].get((c, x)))
    con = pd.concat([con, part], axis=1)

相关问题