首页 > 解决方案 > 将外键从一个数据帧附加到另一个数据帧的最快方法

问题描述

这让我很沮丧,因为我确信这很容易做到,但我终其一生都无法提出最佳解决方案。

基本上假设我有df1,它有列vehiclecheckpoint,代表比赛中每辆车在单圈中通过每个检查点的时间。但是没有记录同一场比赛的某些检查站。

然后我有df2其中包含一个包含检查点数据的单列checkpoint,这些数据应该包含在df1.

我试图找到一种快速的方法来将这些检查点添加lapdf1.

例如: df1 = pd.DataFrame({'vehicle': [1,1,2,2,3,3], 'checkpoint': [1,5,1,5,1,5]}) df2 = pd.DataFrame({"checkpoints": range(2,5)})

我想要的是快速生成一个数据框,将所有 df2 缺失的检查点添加到 df1 中的每辆车,以便生成的数据框对于 3 辆独特的车辆中的每一辆都有检查点 1 到 5。

预期输出如下所示,但检查站和车辆不一定要按顺序排列。重要的是所有 5 个检查点都包含在所有 3 辆车中:

vehicle checkpoints
0   1   1
1   1   2
2   1   3
3   1   4
4   1   5
5   2   1
6   2   2
7   2   3
8   2   4
9   2   5
10  3   1
11  3   2
12  3   3
13  3   4
14  3   5

I've come up with solutions using list comprehensions and concatenation but it's far too slow on larger datasets. I'm not the most at ease with using apply either, so if there's a way to use apply or an entirely different and faster solution, I would be very much appreciative.

If you need more information don't hesitate to ask.


标签: pythonpandas

解决方案


import pandas as pd
df1 = pd.DataFrame({'vehicle': [1,1,2,2,3,3], 'checkpoint': [1,5,1,5,1,5]}) 
df2 = pd.DataFrame({"checkpoint": range(2,5)})

merge基于解决方案

连接df1和完全外部合并来自df1和缺少检查点的独特车辆df2

pd.concat([df1,
           pd.merge(df1[['vehicle']].drop_duplicates().assign(temp=1),
                    df2.assign(temp=1), how='outer').drop('temp', axis=1)]
         ).sort_values(['vehicle', 'checkpoint']).reset_index(drop=True)

输出如 OP 所示。


reindex基于解决方案

import itertools

all_vehicles = df1.vehicle.unique().tolist()
all_checkpoints = (df1.checkpoint.unique().tolist()
                   + df2.checkpoint.unique().tolist())

(df1.set_index(['vehicle', 'checkpoint'])
    .reindex(index=itertools.product(all_vehicles, all_checkpoints))
    .reset_index())

推荐阅读