我有两个数据帧df1和df2,我想根据来自两个列的迭代号将它们组合在一起

df1 =
    iteration   IOPS    Latency
0   1_1 46090   0.7300
1   2_2 12  0.0221
2   3_3 49164   0.1236
3   4_4 98311   0.1318
4   5_5 196604  0.2076
5   6_6 249843  0.1467
6   7_7 298974  0.1578
7   8_8 348108  0.1604
8   9_9 397230  0.1707


df2 = 
    iteration   IOPS    Latency
0   1_1 46074   0.6977
1   2_2 12  0.0279
2   3_3 49159   0.1921
3   4_4 98307   0.2189
4   5_5 298976  0.2337
5   6_6 397265  0.2622

我需要组合df1中的迭代1_1、2_2、3_3、9_9和1_1、2_2、5_5、6_6

df3 = 
iteration  IOPS Latency iteration IOPS Latency
1_1  46090   0.7300    1_1 46074   0.6977
2_2     12   0.0221    2_2 12  0.0279
3_3  49164   0.1236    5_5 298976  0.2337
9_9  397230   0.1707   6_6 397265  0.2622
   

推荐答案

您可以根据迭代ID列表对齐DataFrame,然后是concat:

def align(df, lst):
    return (df.set_index('iteration')
              .reindex(lst)
              .reset_index()
            )

out = pd.concat([align(df1, ['1_1', '2_2', '3_3', '9_9']),
                 align(df2, ['1_1', '2_2', '5_5', '6_6']),
                ], axis=1)

如果您有两个以上的DataFrame,则使用itertools.starmap作为更通用的选项:

from itertools import starmap

dfs = [df1, df2]
iters = [['1_1', '2_2', '3_3', '9_9'],
         ['1_1', '2_2', '5_5', '6_6'],
        ]

def align(df, lst):
    return (df.set_index('iteration')
              .reindex(lst)
              .reset_index()
            )

out = pd.concat(starmap(align, zip(dfs, iters)), axis=1)

print(out)

输出:

  iteration    IOPS  Latency iteration    IOPS  Latency
0       1_1   46090   0.7300       1_1   46074   0.6977
1       2_2      12   0.0221       2_2      12   0.0279
2       3_3   49164   0.1236       5_5  298976   0.2337
3       9_9  397230   0.1707       6_6  397265   0.2622

Python相关问答推荐

三个给定的坐标可以是矩形的点吗

通过优化空间在Python中的饼图中添加标签

max_of_three使用First_select、second_select、

我们可以为Flask模型中的id字段主键设置默认uuid吗

在vscode上使用Python虚拟环境时((env))

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

当点击tkinter菜单而不是菜单选项时,如何执行命令?

mypy无法推断类型参数.List和Iterable的区别

未调用自定义JSON编码器

Cython无法识别Numpy类型

使用__json__的 pyramid 在客户端返回意外格式

使用类型提示进行类型转换

如何训练每一个pandaprame行的线性回归并生成斜率

极柱内丢失类型信息""

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?

Django抛出重复的键值违反唯一约束错误

如何将一个文件的多列导入到Python中的同一数组中?

从列表中分离数据的最佳方式

极点用特定值替换前n行

如何在Python中画一个只能在对角线内裁剪的圆?