首页 > 解决方案 > 如何映射和连接值两个数据框python

问题描述

一个数据框作为

first = pd.DataFrame({'Code': [1,2,3,4],'Value': ['Apple','Ornage','Bannana', 'Graps']})

在此处输入图像描述

另一个数据框是

second= pd.DataFrame({'Code': ['1','2','1','2,4','3'],'Product id': ['A','B','C', 'D','E']})

在此处输入图像描述

我要求将代码替换为'Required field'python 编码中第三个表列中的值。作为数据框

third= pd.DataFrame({'Code': ['1','2','1','2,4','3'],'Product id': ['A','B','C', 'D','E'],'Required Field':['Apple(1)','Orange(2)','Apple(1)','Orange(2),Graps(4)','Bannana(3)']})

在此处输入图像描述

标签: pythonpandasdictionaryreplace

解决方案


尝试:

second["Code"] = second["Code"].str.split(",")
second = second.explode("Code")

first["Code"] = first["Code"].astype(str)
second["Code"] = second["Code"].astype(str)
third = pd.merge(first, second, on="Code")

third["Value"] = third.apply(lambda x: f"{x['Value']}({x['Code']})", axis=1)

print(
    third.groupby("Product id", as_index=False)
    .agg({"Code": ",".join, "Value": ",".join})
    .rename(columns={"Value": "Required Field"})
)

印刷:

  Product id Code      Required Field
0          A    1            Apple(1)
1          B    2           Orange(2)
2          C    1            Apple(1)
3          D  2,4  Orange(2),Graps(4)
4          E    3          Bannana(3)

推荐阅读