python - 如何映射和连接值两个数据框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)']})
解决方案
尝试:
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)
推荐阅读
- python - botocore.exceptions.WaiterError: Waiter InstanceRunning failed: Invalid id: "instance_id"
- c# - ProtectData 类使用哪种加密算法?
- laravel - Laravel guzzle 请求在修补程序上工作但在控制器中未经授权
- node.js - 对某些案例问题做出反应警告计算匹配?
- csv - 在 gnuplot 中绘制轮廓,如下图所示
- python - 为什么输入函数总是返回一个字符串?
- python - 将向量排列成矩阵的向量化方法(numpy)
- excel - “对象变量或未设置块变量”错误来了
- r - 如何使用曲面制作 3D 图
- python - Homebrew - `python@3` 和 `python3` 有什么区别?