首页 > 解决方案 > 将数据帧结果连接到另一个数据帧

问题描述

所以我想尝试将数据帧结果连接到另一个。基本上,我有 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

标签: pythonpandasconcatenation

解决方案


我认为您需要DataFrame通过附加然后concat在外部循环创建 s 列表:

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)

推荐阅读