一個資料框架作為
。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']})
我需要在Python編碼中用值替換第三個表列'Required field'。
third= pd. DataFrame({'Code': ['1','2','1'。 '2,4','3'],'Product id': ['A'/span>,'B'/span>,'C'/span>。'D','E'],'必填專案'。 ['Apple(1)','Orange(2)','Apple(1)'。 'Orange(2),Graps(4)'/span>,'Bannana(3)']})
uj5u.com熱心網友回復:
嘗試:
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": "必填欄位"})
)
印刷品:
產品id代碼必填欄位
0 A 1 蘋果(1)
1 B 2 橙色(2)
2 C 1 蘋果(1)
3 D 2,4 桔子(2),葡萄(4)
4 E 3 Bannana(3)
uj5u.com熱心網友回復:
>>> df1=pd. DataFrame({"code"/span>: [1,2,3,4], "value"/span>: ["apple", "orange", "banana", "grapes"]})
>>> df1
代碼值
0 1 蘋果
1 2 orange
2 3 香蕉
3 4 葡萄
>>> df2=pd. DataFrame({"id": ['A'/span>,'B'/span>,'C'/span>, 'D','E'], "code": ["1","2","1","2,4", "3"]})
>>> df2
id代碼
0 A 1
1 B2
2 C 1
3 D 2、4
4 E 3
將字串轉換為串列,并映射來自另一個資料框架的值:
>>> df2['code'/span>]=df2['code'/span>]。 str.split(',') 。 apply(lambda x: df1.set_index('code') 。 loc[[int(i) for i in x]].value.tolist())
>>> df2
id代碼
0 A [apple]
1 B [orange]
2 C [蘋果]
3 D [橘子、葡萄]
4 E [香蕉]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311659.html
標籤:
上一篇:Python。回圈嵌套字典的問題
下一篇:根據某個模板制作一個陣列



