【问题标题】:concatenate dataframe result to another dataframe将数据帧结果连接到另一个数据帧
【发布时间】:2021-02-23 17:11:41
【问题描述】:

所以我想尝试将数据帧结果连接到另一个。基本上,我有 for 循环遍历要放入函数的列表的每个元素以及要连接到另一个数据帧的结果函数。我尝试使用下面的代码,但变量“final”没有连接数据框,只是得到了循环的最后一个结果。任何人都可以帮助我吗?谢谢

for i in range(len(gene_result)):
    result = pd.DataFrame()
    test = dummy_fitness(gene_result[i])  # function that resulted into dataframe
    coords = 'gen '+ str(i) +' coords'
    fitness_points = 'gen ' + str(i) + ' points'
    result[coords] = test.pudo_coords # getting the particular column i want
    result[fitness_points] = test.fit # getting the particular column i want
    final = pd.concat([result])

“结果”变量如下所示,每个循环都会有所不同。我想将变量“结果”连接到变量“最终”

              gen 0 coords               gen 0 points
0   -6.18360560071739,106.833802730435  8.128732
1   -6.19583084820588,106.850715008823  6.396317
2   -6.17002786742308,106.840075203846  6.050418
3   -6.1956966496,106.822705886667      5.976020
4   -6.18757562077778,106.845673922222  5.703797
5   -6.18317963676,106.81405708         5.622984
6   -6.18141226474074,106.822889814815  5.564183

【问题讨论】:

    标签: python pandas concatenation


    【解决方案1】:

    我认为您需要通过追加创建DataFrames 列表,然后在外部循环中创建concat:

    dfs = []
    for i in range(len(gene_result)):
        result = pd.DataFrame()
        test = dummy_fitness(gene_result[i])  # function that resulted into dataframe
        coords = 'gen '+ str(i) +' coords'
        fitness_points = 'gen ' + str(i) + ' points'
        result[coords] = test.pudo_coords # getting the particular column i want
        result[fitness_points] = test.fit # getting the particular column i want
        dfs.append(result)
    final = pd.concat(dfs, axis=1)
    

    【讨论】:

      【解决方案2】:

      我认为你的结果变量已经是一个数据框 - 你可以像这样连接

      final = final.append(result)
      

      【讨论】:

        【解决方案3】:

        修改代码最简单的方法就是预先声明 final 并运行它

        final = pd.concat([final, result], axis=1). 
        

        或者,当i 是0 时,您可以设置final = result,而不是预先声明final。

        【讨论】:

          猜你喜欢
          • 2022-10-12
          • 1970-01-01
          • 2018-02-23
          • 1970-01-01
          • 1970-01-01
          • 2022-12-07
          • 2018-01-26
          • 1970-01-01
          • 2021-01-24
          相关资源
          最近更新 更多