gpt4 book ai didi

python - 两个 DataFrame 的复杂合并

转载 作者:行者123 更新时间:2023-12-03 19:40:02 24 4
gpt4 key购买 nike

我有两个数据帧:
df1:

                     top1 top2 top3
693541495124446625 US GB CN
912819499544441670 US CN TW
df2:
                         US   GB    CN    TW  \ ...

693541495124446625 939.00 932.00 806.00 789.00 ...
912819499544441670 992.00 646.00 981.00 796.00 ...
如何合并或迭代两个数据帧以获得以下结果:
                       top1          top2          top3
693541495124446625 'US 939.00' 'GB 932.00' 'CN 806.00'
912819499544441670 'US 992.00' 'CN 981.00' 'TW 796.00'
我知道我可以迭代取 df1 值并将该值作为列 [loc] 放入 df2 中通过几个 for 循环,但有没有优化的解决方案?

最佳答案

你可以用 df.replace 试试这个

u = df2.astype(str).radd(df2.columns+' ')
out = df1.T.replace(u.T).T
或者:
u = df2.astype(str).radd(df2.columns+' ')
df1.T.replace(u.to_dict('index')).T
print(out)
top1 top2 top3
693541495124446625 US 939.0 GB 932.0 CN 806.0
912819499544441670 US 992.0 CN 981.0 TW 796.0

关于python - 两个 DataFrame 的复杂合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66371370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com