【问题标题】:Complex merge of two DataFrames两个 DataFrame 的复杂合并
【发布时间】:2021-05-27 23:33:15
【问题描述】:

我有两个 DataFrame:

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 ...

如何合并或迭代两个 Dataframe 以获得以下结果:

                       top1          top2          top3
693541495124446625    'US 939.00'  'GB 932.00'   'CN 806.00'
912819499544441670    'US 992.00'  'CN 981.00'   'TW 796.00'

我知道我可以通过几个 for 循环迭代获取 df1 值并将该值作为列 [loc]ation 放入 df2 中,但是有没有优化的解决方案?

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    你可以用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
    

    【讨论】:

      【解决方案2】:

      类似

      out = df1.T.replace(df2.T).astype('str').radd(df1.T+' ').T
      Out[317]: 
                              top1      top2      top3
      693541495124446625  US 939.0  GB 932.0  CN 806.0
      912819499544441670  US 992.0  CN 981.0  TW 796.0
      

      【讨论】:

        【解决方案3】:

        首先,将第二个数据框变成字典字典:

        df2_dict = {i:None for i in df2.index}
        
        for key in df2_dict:
            df2_dict[key] = {col: df2.loc[key, col] for col in df2.columns}
        

        然后您可以创建一个与 ds1 具有相同行和列的新 df,并对其进行迭代:

        df3 = pd.DataFrame(index=df1.index,
                           columns=df1.columns)
        
        for i in df3.index:
            for col in df3.columns:
                df3.loc[i, col] = df1.loc[i, col] + ' ' + str(df2_dict[i][df1.loc[i, col]])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-24
          • 2019-08-27
          • 2013-03-27
          • 1970-01-01
          • 2019-05-22
          • 2022-11-10
          • 2013-05-05
          • 2016-02-03
          相关资源
          最近更新 更多